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

She*_*ohn 2 c++ operator-overloading implicit-conversion c++11

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());
}
Run Code Online (Sandbox Code Playgroud)

编译错误是:

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

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

Bri*_*ian 7

operator bool()for std::functionis explicit,因此它不能用于复制初始化.你可以实际进行直接初始化:

bool yes(f = the_answer);
Run Code Online (Sandbox Code Playgroud)

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

// this is fine (although compiler might warn)
if (f = the_answer) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)