On 04/29/2015 03:48 PM, Dennis Ritchie wrote:

Thanks. And how can I stop all attempts to perform actions
arifmiticheskih the type int? Ie action to "t += b;" suppressed to compile.

Some operator overloading is needed. I am pretty sure someone must have implemented such a type. What I add below probably addresses just what you ask. I would like to see others chime in with their solutions or potentially the solutions that are already in Phobos.

Continued inline...


-----
import std.exception, std.stdio;

struct CustomInteger(T, T minValue, T maxValue)
{
     T value_;

     alias value this;

     @property T value() const
     {
         enforce((value_ >= minValue) &&
             (value_ <= maxValue));

         return value_;
     }

     @property void value(T v)
     {
         value_ = v;
     }

Add this:

    ref CustomInteger opOpAssign(string op, T2)(T2 rhs)
    {
        static if (is (T2 == CustomInteger)) {
            mixin("value_ " ~ op ~ "= rhs.value_;");
            return this;

        } else {
            return this.opOpAssign!(op, CustomInteger)(CustomInteger(rhs));
        }
    }


}

void main()
{
     alias Balance = CustomInteger!(int, -32_000, 32_000);

     auto b = Balance(42);

     // b += 5; // Error: 'b += 5' is not a scalar,
     // it is a CustomInteger!(int, -32000, 32000)

Now this works:

    b += 5;
    assert(b == 47);

    b += b;
    assert(b == 94);



     int t = 4;

     t += b; // OK

     writeln(b); // prints 46
}

Ali

Reply via email to