DMD can implicitly convert class pointer to the bool. Is it bug or terrible feature?

Maxim Fomin maxim at maxim-fomin.ru
Sun Nov 24 06:45:30 PST 2013


On Sunday, 24 November 2013 at 14:24:09 UTC, ilya-stromberg wrote:
> On Sunday, 24 November 2013 at 14:17:50 UTC, Dicebot wrote:
>> Not exactly. It is all about "if" condition. AFAIK, D defines 
>> that condition `if(X)` get re-written to `if(cast(bool)X)` 
>> before semantic pass. So it is kind of implicit explicit 
>> conversion :)
>
> Not exactly.
>
> Code:
>
> bool b = f;
>
> DMD output:
>
> Error: cannot implicitly convert expression (f) of type Foo to 
> bool
>
>
> But code:
>
> bool b = !f;
>
> compiles.

Because '!' operator provides boolean context. It is written in 
the spec, although not explicitly. By the way, the same happens 
with objects with pretty many types (except structs which do not 
provide necessary operator overloads), so classes are not 
exceptional here.

UnaryExpression:
     & UnaryExpression
     ++ UnaryExpression
     -- UnaryExpression
     * UnaryExpression
     - UnaryExpression
     + UnaryExpression
     ! UnaryExpression
     ComplementExpression
     ( Type ) . Identifier
     ( Type ) . TemplateInstance
     DeleteExpression
     CastExpression
     PowExpression


More information about the Digitalmars-d mailing list