Stas
Stas

Reputation: 11771

Unary negation operator overloading in D

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 on dmd 2.053, 2.054

What's wrong with my code?

Upvotes: 5

Views: 234

Answers (1)

Robert
Robert

Reputation: 436

You cannot overload the ! operator in D - see http://www.d-programming-language.org/operatoroverloading.html#Unary for a list of overloadable unary operators. Without knowing what you're doing, it's hard to suggest a work around, it might be worth looking at alias this though - http://www.d-programming-language.org/class.html#AliasThis.

Upvotes: 3

Related Questions