【发布时间】:2015-05-21 23:15:45
【问题描述】:
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。
【问题讨论】:
-
你想做什么?调用函数?
-
如果你愿意,你可以回答。请注意,
f = the_answer; if (f) {...}也有效。
标签: c++ c++11 operator-overloading implicit-conversion