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

Why std::function does not implicitly convert to bool in C++11?

考虑以下代码。

#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 变量不起作用,而操作的结果或在 if() 语句中使用它是可以的。

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

我为 b = f1 行所做的工作是好的 ol' 双爆炸:!!。在如此现代的 C++ 代码中,它看起来像古董。

编辑:这也编译:

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

请注意 std::function::operator bool is explicit conversion function, implicit conversion is not allowed. So bool b = f1; won't work. (Explicit conversion will work well if you use static_cast 类似于 bool b = static_cast<bool>(f1);。)

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

ifoperator!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.