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.
- Jonathan M Davis
I hadn't fully understood alias this, i.e. that one may alias
what becomes effectively a conversion function of no arguments.
Thank you for pointing me in that direction.