just an idea (!! operator)

monarch_dodra monarch_dodra at gmail.com
Wed Jul 11 04:47:59 PDT 2012


On Wednesday, 11 July 2012 at 11:18:21 UTC, akaz wrote:
> if needed, the operator !! (double exclamation mark) could be 
> defined.

Problem is that operator"!!" is already used asa  twin 
operator"!". This is shorthand for "is valid as bool":

When a type can be casted to bool, it is quicker to write "!!val" 
than "cast(bool)val".

This is only moderately useful, as 90% of the time, the cast 
occurs in a if/while/for, where implicit casts to bool are legal, 
but still:

----
import std.stdio;

struct S
{
   int v;
   bool opCast() {return cast(bool)v;}
}

void foo(bool b){}

void main()
{
   S s = S(5);
   //bool b = s; //Error: cannot implicitly convert expression (s) 
of type S to bool
   bool b = !!s; //This is valid though, and shorter than //bool b 
= cast(bool)s;
   if(s) //But it works inside a if anyways
     ...

   foo(!!s); //Call foo with s as boolean
}
----

I've seen this used a lot in c++. explicit casts did not exist 
prior to c++11. To allow casting to bool while avoiding the 
dangers of implicit casts, one design patter was to define "only" 
operator"!", and use !!val as an alternative to casting to bool.

After you've seen it a few times, it feels natural, as if it was 
an operator of itself.

I wouldn't be surprised if this is happening in D, so I don't 
think "!!" can be taken for anything.


More information about the Digitalmars-d mailing list