and/or/not/xor operators

Simen Kjaeraas simen.kjaras at gmail.com
Thu May 30 09:46:47 PDT 2013


On 2013-05-30, 13:56, Shriramana Sharma wrote:

> Hello. I have always loved the readability of C++'s and/or/not/xor
> word-like logical operators but It doesn't seem to be available in D.
> Isn't this possible in D? I tried doing:
>
> alias && and ;
> import std.stdio ;
> void main () {
> 	writeln ( true and true ) ;
> }
>
> but I get errors:
>
> $ dmd foo.d
> foo.d(1): Error: basic type expected, not &&
> foo.d(1): Error: no identifier for declarator int
> foo.d(1): Error: semicolon expected to close alias declaration
> foo.d(1): Error: Declaration expected, not '&&'
> foo.d(7): Error: found 'and' when expecting ',
>
> Thanks.

While that's not possible, D's operator overloading allows you to
implement it yourself:

struct And {
     struct AndImpl {
         private bool payload;
         this( bool value ) {
             payload = value;
         }
         bool opBinary(string op : "/")(bool value) const {
             return payload && value;
         }
     }
     AndImpl opBinaryRight(string op : "/")(bool value) {
         return AndImpl( value );
     }
}

struct Or {
     struct OrImpl {
         private bool payload;
         this( bool value ) {
             payload = value;
         }
         bool opBinary(string op : "/")(bool value) const {
             return payload || value;
         }
     }
     OrImpl opBinaryRight(string op : "/")(bool value) {
         return OrImpl( value );
     }
}

And and;
Or or;


void main( ) {
     assert( true /and/ true );
     assert( true /or/ false );
}

Of course, if you ever use this, watch out for the flood of WTFs
and curse words.

-- 
Simen


More information about the Digitalmars-d-learn mailing list