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

时间:2015-05-21 23:15:46

标签: c++ c++11 operator-overloading implicit-conversion

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.

编辑我没有看到explicit关键字..没有隐式转换,我想我必须使用static_cast

1 个答案:

答案 0 :(得分:7)

operator bool()的{​​p> std::functionexplicit,因此无法用于复制初始化。您实际上可以进行直接初始化:

bool yes(f = the_answer);

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

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