E.g if I wanted to make a SafeInt struct, that behaves otherwise
just like an int, but when operators like +=, *=, ++, -- etc are
used with it, my custom SafeInt operators would check that
there's no integer overflow.

If you use alias this to _reveal_
the internal int value of SafeInt, then that int value's default
operators are used, and thus no overflow checking.

Wouldn't you have the exact same problem with implicit casts in C++? If you want to use custom operators, you should just define those, same as you would in C++. You can even implement just some operators and use alias this for functionality that you don't want to reimplement, like this:

import std.stdio;

struct A
{
    int a;
    alias a this;
    auto opOpAssign(string op, T)(T b)
        if(op == "+" && is(typeof(a += T.init)))
    {
        a += b;
        writeln("opOpAssign!\"+\" called.");
    }
}


void main()
{
    auto a = A(3);
    a += 5u;
    writeln(a);
    writeln(a - 1);
}

This prints:

opOpAssign!"+" called.
8
7

Reply via email to