Why does an implicit conversion occur in an "if expression", although it must be an explicit conversion

This code should not compile, so why is it? what is the principle of context in an if statement?

class B { public: B() {} explicit operator bool () {} }; int main (){ B Bp; //bool check = Bp // error if (Bp){ //ok return 1; } return 0; } 

thanks

+4
source share
1 answer

This code really needs to compile. The standard has spent a lot of effort to ensure its implementation.

There are several places where the expression "contextually converted to bool". In these places, explicit bool conversions will be called, if available. One such contextual transformation is the if , as in your case.

This language allows the use of explicit operator bool types for conditional checking if(expr) , but you cannot use other things without an explicit conversion. You cannot pass it to a function that accepts a bool ; you cannot return it from a function that returns bool , etc.

All contextual transformations are explicit expressions in language functions. Thus, an explicit operator bool protects you from implicit user conversions, but allows for transforms defined by the language.

+3
source

Source: https://habr.com/ru/post/1497700/


All Articles