explicit specifier doesn't seem to work when converting an object to bool
Asked Answered
L

2

13

I am learning C++ recently and I noticed an example on cppreference, part of which goes like this:

struct B
{
    explicit B(int) { }
    explicit operator bool() const { return true; }
};

int main()
{
    B b2(2);       // OK: direct-initialization selects B::B(int)
    if (b2) ;      // OK: B::operator bool()
}

The introduction to implicit conversions tells me "when the expression is used in an if statement or a loop" the result of this expression( b2 ) will be converted into bool type implicitly.

Also, the introduction to explicit specifier tells me if "a conversion function is explicit, it cannot be used for implicit conversions".

Since b2 will be converted implicitly in if(b2), and the conversion function is explicit, how comes if(b2) is ok?

Logway answered 29/1, 2019 at 15:31 Comment(1)
Maybe reated: #39996073Forereach
S
15

Contextual conversion is special; since C++11, explicit conversion functions will be considered in contextual conversions.

(emphasis mine)

(since C++11)

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;
  • the operands of the built-in logical operators !, && and ||;
  • the first operand of the conditional operator ?:;
  • the predicate in a static_assert declaration;
  • the expression in a noexcept specifier;
  • the expression in an explicit specifier; (since C++20)
  • the predicate of a contract attribute. (since C++20)

That means for if (b2), b2 will be converted to bool implicitly by B::operator bool() even it's declared as explicit.

Sparkie answered 29/1, 2019 at 15:35 Comment(0)
V
7

Read further in your own link. Contextual conversions occur implicitly even for explicit conversions:

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;
  • the operands of the built-in logical operators !, && and ||;
  • the first operand of the conditional operator ?:;
  • the predicate in a static_assert declaration;
  • the expression in a noexcept specifier;
  • the expression in an explicit specifier;
  • the predicate of a contract attribute.
Varnado answered 29/1, 2019 at 15:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.