Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How is 'if (x)' where 'x' is an instance of a class, not an implicit conversion?

According to cppreference.com an explicit conversion function cannot be used for implicit conversions. As an example they have this:

struct B
{
    explicit B(int) { }
    explicit B(int, int) { }
    explicit operator bool() const { return true; }
};
 
int main()
{
    ...
    if (b2) ;      // OK: B::operator bool()
    ...
}

I would have thought that ‘if (b2)’ was an implicit conversion and therefore not able to use the explicit conversion function. So what would be an example of an implicit conversion that wouldn’t be allowed?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Contextual conversions

In the following contexts, the type bool is expected and the
implicit conversion is performed if the declaration bool t(e); is
well-formed (that is, an explicit conversion function such as explicit
T::operator bool() const; is considered). Such expression e is said to
be contextually converted to bool.

  • the controlling expression of if, while, for;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading