是安全bool成语在C ++ 11过时吗? [英] Is the safe-bool idiom obsolete in C++11?

查看:295
本文介绍了是安全bool成语在C ++ 11过时吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@R的此回答。 Martinho Fernandes 表明,安全bool成语在C ++ 11中已被弃用,因为它可以被一个简单的

替换。

  explicit operator bool()const; 


根据标准报价在回答§4[conv] / code>:


表达式e可以隐式转换为 T 如果且仅当声明 T t = e; 形式良好时,对于一些发明的临时变量 t (§8.5)。某些语言结构要求将表达式转换为布尔值。在这种上下文中出现的表达式 e 被称为上下文转换 bool 如果且仅当声明 bool t(e); 形式良好,对于一些发明的临时变量t )。


突出显示的部分清楚地显示了隐式显式转换(在标准中称为上下文转换)为@R。






















$ b b

  • if while code>(§6.4[stmt.select] p4

  • 二进制逻辑运算符& & || §5.14[expr.log.and / or] p1 for each)

  • 逻辑否定运算符§5.3.1[expr.unary.op ] p9

  • 条件运算符?:§5.14[expr。 cond] p1

  • static_assert §7[dcl.dcl] p4 )

  • noexcept §15.4[except.spec] / code>)



标题中的假设是否正确?我希望我们没有忽略任何潜在的缺点。

解决方案

是的。这是 示例,仅限于具有隐式用户定义转换的问题,而显式用户定义的转换运算符实际上因为这个问题而发生的事件,并用更清晰,更合乎逻辑的东西替换所有的safe-bool东西。


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.

解决方案

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.

这篇关于是安全bool成语在C ++ 11过时吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆