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

C++C++11DeprecatedC++ FaqSafe Bool-Idiom

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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.

Solution 2 - C++

I wouldn't call it "obsolete". Not everyone is taking the leap to C++11 (not even 1 year old) as of yet. And even if the a good amount of coders were, the ability to keep the code backwards compatible would be a must, considering this kind of idiom seems more sensible for libraries than for programs proper.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionXeoView Question on Stackoverflow
Solution 1 - C++PuppyView Answer on Stackoverflow
Solution 2 - C++Luis MachucaView Answer on Stackoverflow