1

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
mayaknife
  • 302
  • 1
  • 8
  • Implicit conversions are extensively documented on cppreference.com, see: https://en.cppreference.com/w/cpp/language/implicit_conversion – G. Sliepen Dec 13 '21 at 22:05
  • An implicit conversion prevented by your explicit bool operator would be: `int x = b2;` – paddy Dec 13 '21 at 22:18
  • @paddy Wouldn't that be a copy-initialization rather than an implicit conversion? – mayaknife Dec 13 '21 at 22:51

2 Answers2

3

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;
  • ...
bolov
  • 72,283
  • 15
  • 145
  • 224
  • Ah, so by being a contextual conversion that makes it not implicit. I had thought the two to be orthogonal. – mayaknife Dec 13 '21 at 22:53
0

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335