opCast!bool

Timon Gehr timon.gehr at gmx.ch
Tue Jan 3 15:35:20 PST 2012


On 01/04/2012 12:31 AM, Jonathan M Davis wrote:
> On Tuesday, January 03, 2012 17:41:12 simendsjo wrote:
>> I guess this is as designed, but I'll ask anyway.
>>
>> http://dlang.org/operatoroverloading.html#Cast says an expression is
>> rewritten to opCast "whenever a bool result is expected".
>>
>> This is true for
>> if(e) somethingElse
>> and e&&  somethingElse
>>
>> , but not for other parts.
>> assert(cast(bool)e == true); // explicit cast works
>> assert(e == true); // Error: incompatible types for ((s) == (false)):
>> 'S' and 'bool'
>>
>> is(typeof(e) : bool); // false
>
> Yeah. It's the same for built-in types. Take arrays and pointers for example.
> They don't implicitly convert to bool, but when you use them in a condition,
> they implicitly convert to bool (true if they're non-null, false if they're
> null). If you want implicit conversion in general, then you need to use alias
> this.
>
> - Jonathan M Davis

The conversion is explicit. if(x) is rewritten to if(cast(bool)x) and e 
&& somethingElse is rewritten to cast(bool)e && cast(bool)somethingElse.


More information about the Digitalmars-d-learn mailing list