Overload of ! operator

Jonathan M Davis jmdavisProg at gmx.com
Tue Jun 25 22:07:47 PDT 2013


On Wednesday, June 26, 2013 06:59:14 cal wrote:
> On Wednesday, 26 June 2013 at 04:06:05 UTC, Jonathan M Davis
> 
> wrote:
> > 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).
> > So, if you need to be able to do !obj in the general case,
> > that's not going to
> > work
> 
> ...
> 
> import std.stdio;
> 
> struct S {
>    int x;
>    bool opCast(T)() if (is(T == bool)) {
>      return x == 0;
>    }
> }
> 
> void main() {
>    auto s = S(1);
>    auto b = !s;
>    writeln(b);	// true
> }
> 
> Is this not supposed to work?

No, it's not. That would require an implicit cast (which requires using alias 
this). opCast gives you an explicit cast only. Where that becomes confusing is 
the fact that the compiler inserts explicitly casts to bool in conditions for 
if statements, loops, and the ternary operator. e.g.

if(foo) {...}

becomes

if(cast(bool)foo) {...}

So, if you've overloaded opCast to bool, then it'll get used in the conditions 
for if statements, loops, and the ternary operator. But no explicit cast is 
added just for putting ! in front of a variable. It works with something like

if(!foo) {...}

simply because that becomes

if(!cast(bool)foo) {...}

But nothing special is done for !, and !a will not call opCast.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list