Implicit conversion to bool, and other conversions.
Jonathan M Davis
jmdavisProg at gmx.com
Fri Aug 16 15:11:09 PDT 2013
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.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list