Implicit conversion to bool, and other conversions.

Carl Sturtivant sturtivant at gmail.com
Fri Aug 16 21:32:22 PDT 2013


On Friday, 16 August 2013 at 22:11:24 UTC, Jonathan M Davis wrote:
> On Friday, August 16, 2013 23:18:51 Carl Sturtivant wrote:
>> The operator overloading page in the Language Reference and the
>> operator overloading discussion in TDLP say different things 
>> about
>> T opCast(bool)() if(is(T==bool))
>> and experimentally it seems that in any context where a bool is
>> expected and x occurs (where x is a struct with such an opCast
>> defined) then x will be rewritten as its conversion to bool 
>> using
>> that opCast.
>> 
>> Please confirm that the above is generally true or tell me the
>> exact rules.
>> 
>> Are there any other implicit conversions possible in D (apart
>> from int to long, int to double and so forth)?
>
> opCast is only ever for explicit conversions. alias this is 
> used for implicit
> conversions.
>
> Whether things get confusing is that there are places where the 
> compiler
> inserts casts for you, so it _looks_ like there's an implicit 
> conversion, but
> there isn't really. In particular, cast(bool) is inserted in 
> the conditions of
> if statements, loops, ternary operators, and assertions. So, if 
> you have
> something like
>
> if(a) {}
>
> it becomes
>
> if(cast(bool)a) {}
>
> So, if you want to use a struct in a condition, you overload 
> opCast for bool,
> but if you want it to implicitly convert to bool in general, 
> then you use
> alias this.


The conversion to bool via opCast seems more general than that: 
the following compiles and runs.

void main() {
	A x;
	if( x && f(99)) writeln( "yes!");	
	bool b = f(201) && x;
	writeln( b);
}

struct A {
	bool opCast(T)() if( is( T==bool)) { return true; }
}

bool f(int x) {
	return x%2 == 1;
}

And the online docs here
   http://dlang.org/operatoroverloading.html#Cast
say "etc., whenever a bool result is expected".
So that seems likely to happen in arbitrary logical expressions, 
in fact in any context where a bool is expected perhaps.



More information about the Digitalmars-d-learn mailing list