No viable conversion from std::function to bool

2019-02-19 22:07发布

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条回答
The star\"
2楼-- · 2019-02-19 23:00

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) {
    // ...
}
查看更多
登录 后发表回答