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

扶醉桌前 提交于 2019-12-27 10:20:08

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6242768/is-the-safe-bool-idiom-obsolete-in-c11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!