c++ - 为什么 std::function 在 C++11 中不隐式转换为 bool?

标签 c++ function c++11 implicit-conversion std-function

<分区>

考虑以下代码。

#include <functional>

int main(void)
{
    std::function<void()> f1;
    if (f1) { /* ok */
        ...
    }

    bool b = f1; /* compile-error */
    bool B = !f1; /* ok */
    ...
}

std::function<>在某些情况下隐式转换为 bool,但并非在所有情况下。将其分配给 bool -variable 不起作用,而操作的结果或在 if() 中使用它-声明是正确的。

为什么会这样?看来我们必须对其进行 bool 运算,然后才能进行转换。

我为使工作成为 b = f1 所做的工作-line 是好的 ol' double bang:!! .在如此现代的 C++ 代码中,它看起来像古董。

编辑:这也编译:

bool b = f1 || f1; /* OK */

最佳答案

请注意 std::function::operator boolexplicit转换函数,不允许隐式转换。所以bool b = f1;不会工作。 (如果你像使用 bool b = static_cast<bool>(f1); 那样使用 static_cast,显式转换会很好地工作。)

using it in an if()-statement is OK.

if一起使用时, operator!operator|| , contextual conversions会生效,会考虑显式转换函数。

(C++11 起)

In the following five contexts, the type bool is expected and the implicit conversion sequence is built if the declaration bool t(e); is well-formed. that is, the explicit user-defined conversion function such as explicit T::operator bool() const; is considered. Such expression e is said to be contextually convertible to bool.

  • controlling expression of if, while, for;
  • the logical operators !, && and ||;
  • the conditional operator ?:;
  • static_assert;
  • noexcept.

关于c++ - 为什么 std::function 在 C++11 中不隐式转换为 bool?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39590272/

相关文章:

C++11 从 int& 和 long 的算术运算中自动推导类型

c++ - 非类型模板参数的理解

java - 引用父类(super class)(类型化语言)的首选方式

Windows 中的 C++ 高精度时间测量

assembly - 汇编中的函数

java - Java中的继承,无法访问子类函数/方法

c++ - '无法将参数 'float' 的 'float*' 转换为 '1'

.net - Windows 窗体设计器自定义控件更改在运行时正常工作但在设计时不能正常工作的 anchor

c++ - 如何将图标添加到您的 C++ 控制台应用程序?

concurrency - 实验弱有序并发的工具