Implicit conversion to bool, and other conversions.

Ali Çehreli acehreli at yahoo.com
Fri Aug 16 14:35:53 PDT 2013


On 08/16/2013 02:18 PM, 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))

The current syntax is the following:

     bool opCast(T : bool)() const

 > 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.

As far as I know, opCast in general is for explicit type conversions, 
not explicit. However, bool is special: certain language constructs 
(e.g. assert, if, etc.) will make an explicit conversion to bool even 
when the program does not ask for one.

For example, the last line does not compile because opCast is not used 
for converting from S to bool:

struct S
{
     int i;

     bool opCast(T : bool)() const
     {
         return i == 42;
     }
}

void main()
{
     auto s_true = S(42);
     auto s_false = S(43);

     assert(s_true);
     assert(!s_false);

     bool b = s_true;    // compilation ERROR
}

 > 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)?

I know 'alias this' is for implicit conversions.

Ali



More information about the Digitalmars-d-learn mailing list