c++11 - Why implicit conversion is occurring in "if expression" although it should be explicit conversion -
this code not supposed compile , why ? principle of context in if expression ?
class b { public: b() {} explicit operator bool () {} }; int main (){ b bp; //bool check = bp // error if (bp){ //o.k return 1; } return 0; }
thanks
that code supposed compile. standard expended great deal of effort ensure does.
there number of places expression "contextually converted bool" in places, explicit
bool conversions called if they're available. 1 of contextual conversions if
expression, in case.
this language allows explicit operator bool
types still used conditional checking if(expr)
, can't other things without explicit conversion. can't pass function takes bool
; can't return function returns bool
, , forth.
all of contextual conversions explicit expressions in language features. explicit operator bool
protects implicit user-defined conversions, while still allowing language-defined conversions happen.