Overload of ! operator

Eric eric at makechip.com
Tue Jun 25 21:53:46 PDT 2013


On Wednesday, 26 June 2013 at 04:16:30 UTC, Ali Çehreli wrote:
> 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


Thanks for all the insignt. But I think I'm just going to fudge 
this one
with a "bang()" method...

Incidently, for this project I figured out an interesting use of 
alias.
The C++ classes I am wrapping have a lot of virtual methods with 
all primitive arguments.   So I create an D-interface for them, 
and wrap the rest with C methods.  The wrapper class then makes 
methods that call the C methods, and then aliases the interface 
reference to "this" so that the wrapper class instance points to 
both the C++ native methods as well as the C-wrapped methods.

-Eric










More information about the Digitalmars-d-learn mailing list