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 declarationT t=e;
is well-formed, for some invented temporary variablet
(§8.5). Certain language constructs require that an expression be converted to a Boolean value. An expressione
appearing in such a context is said to be contextually converted tobool
and is well-formed if and only if the declarationbool 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.
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.
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.