C++ – Is the safe-bool idiom obsolete in C++11

cc++-faqc++11deprecatedsafe-bool-idiom

This answer of @R. Martinho Fernandes shows, that the safe-bool idiom is apperently deprecated in C++11, as it can be replaced by a simple

explicit operator bool() const;

according to the standard quote in the answer §4 [conv] p3:

An expression e can be implicitly converted to a type T if and only if the declaration T t=e; is well-formed, for some invented temporary variable t (§8.5). 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 (§8.5).

The highlighted part clearly shows the "implicit explicit cast" (called "contextual conversion" in the standard) as @R. Martinho put it.

The "certain language constructs" that require that "implicit explicit cast" seem to be the following:

  • if, while, for (§6.4 [stmt.select] p4)
  • binary logical operators && and || (§5.14 [expr.log.and/or] p1 for both)
  • the logical negation operator ! (§5.3.1 [expr.unary.op] p9)
  • conditional operator ?: (§5.14 [expr.cond] p1)
  • static_assert (§7 [dcl.dcl] p4)
  • noexcept (§15.4 [except.spec] p2)

Is our assumption in the title correct? I hope we didn't overlook any potential drawbacks.

Best Answer

Yes. This is the example for problems with only having implicit user-defined conversions and explicit user-defined conversion operators were practically invented because of this problem and to replace all the safe-bool stuff with something a lot cleaner and more logical.