Overload of ! operator

Ali Çehreli acehreli at yahoo.com
Tue Jun 25 21:16:24 PDT 2013


On 06/25/2013 09:05 PM, Jonathan M Davis wrote:

 > On Wednesday, June 26, 2013 05:35:03 cal wrote:
 >> On Wednesday, 26 June 2013 at 02:50:51 UTC, Eric wrote:
 >>> Is there a way to overload the ! operator?  I can't seem to get
 >>> it to work with the standard unaryOp method.  I need this
 >>> because
 >>> I am making a wrapper for a C++ API that has ! overloaded.
 >>>
 >>> -Eric
 >>
 >> According to http://dlang.org/operatoroverloading.html#Cast, the
 >> following are rewritten:
 >>
 >> if (e) => if (e.opCast!(bool))
 >> if (!e) => if (!e.opCast!(bool))
 >>
 >> So perhaps you need to override opCast!(bool).
 >
 > Yeah, that should work for the conditions in if, while, and for loops but
 > won't work for anything else (_maybe_ ternary operators, but I'm not 
sure).

Works for ternary as well.

The other option is 'alias this' but it is a little dangerous because 
bool is an arithmetic type. So, opCast would be better.

import std.stdio;

struct S
{
     int i;

     bool truth() const
     {
         return i == 42;
     }

     alias truth this;
}

void foo(bool b)
{
     writeln(b);
}

void main()
{
     auto s = S(42);

     if (s){
     }

     while (s) {
         break;
     }

     int i = s ? 4 : 5;

     foo(s);

     // What does it mean?
     writeln(s + 2);
     writeln(!s - 7);
}

 > So, if you need to be able to do !obj in the general case, that's not 
going to
 > work

It surprisingly works both with opCast and 'alias this'.

Ali



More information about the Digitalmars-d-learn mailing list