Overloading the unary negation operator in D

the code

struct test
{
   private real value;

   this(real value)
   {
      this.value = value;
   }

   bool opUnary(string op)() if (op == "!")
   {
      return !value;
   }
}

void main()
{
   test a = 123.12345;
   bool b = !a;
}

Compilation error

prog.d(19): Error: expression a of type test does not have a boolean value

http://ideone.com/Kec81

Also tested by dmd 2.053, 2.054

What is wrong with my code?

+5
source share
1 answer

You cannot overload a statement !in D - see http://www.d-programming-language.org/operatoroverloading.html#Unary for a list of overloaded unary operators. Not knowing what you are doing, it’s hard to offer a job, it might be worth a look at alias this, although - http://www.d-programming-language.org/class.html#AliasThis .

+3
source

All Articles