www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to overload opertators for enums

reply "Tobias Pankrath" <tobias pankrath.net> writes:
This should be a "tribool"-like type.

enum Value : byte { Undef = 0, True = 1, False = -1 };

unittest
{
     with(Value) {
     assert(~Undef == Undef); // failure
     assert(~True  == False);
     assert(~False == True);
}

When I overload opUnary!("~") in this way, unittests fail.

Value opUnary(string op)(Value operand) if(op == "~")
out(result)
{
     with(Value) assert(result == Undef ||
                        result == False ||
                        result == True);
}
body
{
     return cast(Value)(operand * -1);
}

What is the correct way to do this?

This works:
assert(Value.Undef.opUnary!"~"() == Value.Undef);
Jun 26 2012
parent "bearophile" <bearophileHUGS lycos.com> writes:
Tobias Pankrath:

 When I overload opUnary!("~") in this way, unittests fail.
Currently in D you can only overload struct and class operators. Bye, bearophile
Jun 26 2012