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

107 Views Asked by At

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?

2

There are 2 best solutions below

1
bolov On BEST ANSWER

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;
  • ...
0
Vlad from Moscow On

From the C++ 17 Standard (7 Standard conversions)

4 Certain language constructs require that an expression be converted to a Boolean value. An expression e appearing in such a context is said to be contextually converted to bool and is well-formed if and only if the declaration bool t(e); is well-formed, for some invented temporary variable t (11.6).

The declaration

bool t( b2 );

is well-formed because there is used the direct initialization.