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

No viable conversion from std::function to bool

本文关键字:函数 bool 转换 std      更新时间:2023-10-16

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 %.2fn",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) {
    // ...
}