safe-bool 习惯用法在 C++11 中是否已过时?
explicit operator bool() const;
Martinho Fernandes 表明,safe-bool 习语在 C++11 中显然已被弃用,因为它可以根据答案中的标准引用 §4 [conv] p3:
当且仅当声明
T t=e;
对于某些发明的临时变量T t=e;
格式良好时,表达式 e 可以隐式转换为类型T
代码>t(第8.5节)。某些语言结构要求将表达式转换为布尔值。出现在这种上下文中的表达式e
被认为是根据上下文转换为bool
并且是格式正确的当且仅当对于某些发明的临时变量 t (§8.5),声明bool t(e);
格式良好。
突出显示的部分清楚地将“隐式显式转换”(标准中称为“上下文转换”)显示为@R。马蒂尼奥说道。
需要“隐式显式转换”的“某些语言结构”似乎如下:
if
、while
、for
(§6.4 [stmt.select] p4
)- 二元逻辑运算符
&&
和||
(§5.14 [expr.log.and/或] p1
为两者) - 逻辑否定运算符
!
(§5.3.1 [expr.unary.op] p9
) - 条件运算符
?:
(§5.14 [expr.cond] p1
) static_assert
(§7 [dcl.dcl] p4
)noexcept
(§15.4 [ except.spec] p2
)
我们在标题中的假设正确吗?我希望我们没有忽视任何潜在的缺点。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的。这是仅具有隐式用户定义转换和显式用户定义转换运算符的问题的示例,实际上因为这个问题而发明,并用更干净、更合乎逻辑的东西替换所有 safe-bool 东西。
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.
我不会称其为“过时”。到目前为止,并不是每个人都跃迁到 C++11(甚至不到 1 岁)。即使有大量的编码员,保持代码向后兼容的能力也是必须的,考虑到这种习惯用法对于库来说似乎比对于程序本身更明智。
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.