Alias this isn't implemented for implicit conversions to bool in conditional expressions. The following presumably valid code doesn't compile:
--------------------
void main()
{
S s;
if (!s) {} // (4)
}
struct S
{
bool cond;
alias cond this;
}
--------------------
% dmd -o- -c test.d
test.d(4): Error: expression s of type S does not have a boolean value
Comment #1 by rsinfu — 2010-10-08T13:14:45Z
It's simply Expression::checkToBoolean() not looking for alias this. Here's a proposed patch against dmd r707:
====================
--- src/expression.c
+++ src/expression.c
@@ -1269,6 +1269,15 @@ Expression *Expression::checkToBoolean(Scope *sc)
e = e->semantic(sc);
return e;
}
+
+ // Forward to aliasthis.
+ if (ad->aliasthis)
+ {
+ Expression *e = new DotIdExp(loc, this, ad->aliasthis->ident);
+ e = e->semantic(sc);
+ e = e->checkToBoolean(sc);
+ return e;
+ }
}
if (!type->checkBoolean())
====================
Note: Since CastExp takes care of aliasthis, adding a test for ad->aliasthis in a preceding if-block also makes the repro code work. But the if-block doesn't check for implicit convertible-ness (i.e. checkToBoolean), and it will eventually allow the following wrong code to be accepted:
void main()
{
S s;
if (s) {} // wrong
}
struct S
{
struct R {} // not implicitly convertible to bool
R r;
alias r this;
}
Comment #2 by bearophile_hugs — 2010-12-21T01:50:31Z