没有从 std::function 到 bool 的可行转换

No viable conversion from std::function to bool

C++11 std::function 应该实现 operator bool() const,为什么 clang 告诉我没有可行的转换?

#include <functional>
#include <cstdio>

inline double the_answer() 
    { return 42.0; }

int main()
{
    std::function<double()> f;

    bool yes = (f = the_answer);

    if (yes) printf("The answer is %.2f\n",f());
}

编译错误为:

function_bool.cpp:12:7: error: no viable conversion from 'std::function<double ()>' to 'bool'
        bool yes = (f = the_answer);
             ^     ~~~~~~~~~~~~~~~~
1 error generated.

EDIT 我没有看到 explicit 关键字.. 没有隐式转换,我想我将不得不使用 static_cast.

operator bool() 对于 std::functionexplicit,因此它不能用于复制初始化。您实际上可以进行直接初始化:

bool yes(f = the_answer);

但是,我假设它确实用于 上下文转换,当表达式用作条件时会发生这种情况,通常用于 if 语句。与隐式转换不同,上下文转换可以调用 explicit 构造函数和转换函数。

// this is fine (although compiler might warn)
if (f = the_answer) {
    // ...
}