So the task is to write a struct object for the saturation arithmetic. I tried first to write it for the unsigned Types:

struct Saturated(T)
        if (isIntegral!T)
{
        static assert (isUnsigned!T || isSigned!T);

        @property
        {
                static Saturated min() { return Saturated(T.min); }
                static Saturated max() { return Saturated(T.max); }
                static Saturated init() { return Saturated(T.init); }
        }
        Saturated opBinary(string op)(const Saturated rhs) const
                if (op == "+" || op == "-" || op == "/")
        {
                static if (isUnsigned!T){
                        if(rhs.max - rhs._value < _value)
                                return rhs.max;
                        if(rhs._value > _value)
                                return rhs.min;
return Saturated(cast(T)(mixin("_value " ~ op ~ " rhs._value")));
                }
                else{
return Saturated(cast(T)(mixin("_value " ~ op ~ " rhs._value")));
                }
        }

        string toString() const
        {
                import std.conv;
                return to!string(_value);
        }

private:
        T _value;
}

unittest
{
        alias subyte = Saturated!ubyte;
        assert(subyte(254) + subyte(2) == subyte(255));
        assert(subyte(100) + subyte(2) == subyte(102));
        assert(subyte(10) - subyte(11) == subyte(0));
        assert(subyte(128) - subyte(129) == subyte(0));
}

But the last test does not pass. Why does the minus operation is treated in signed datatype, while + is unsigned? Note that I do not know much about templates or methods. So pls execuse me if I do a major mistake here.

Reply via email to