No viable conversion from std::function to bool

ε祈祈猫儿з 提交于 2019-12-19 10:33:12

问题


The C++11 std::function is supposed to implement operator bool() const, so why does clang tell me there is no viable conversion?

#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());
}

The compiling error is:

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

EDIT I didn't see the explicit keyword.. no implicit conversion then, I guess I'll have to use static_cast.


回答1:


operator bool() for std::function is explicit, therefore it cannot be used for copy-initialization. You can actually do direct-initialization:

bool yes(f = the_answer);

However, I assume it's really intended for contextual conversion, which happens when an expression is used as a condition, most often for an if statement. Contextual conversion can call explicit constructors and conversion functions, unlike implicit conversion.

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


来源:https://stackoverflow.com/questions/30385900/no-viable-conversion-from-stdfunction-to-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!