从std :: function到bool没有可行的转换 [英] No viable conversion from std::function to bool
问题描述
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(答案是%.2f \\\
,f());
}
编译错误是:
function_bool.cpp:12:7:错误:没有可行的转换从'std :: function< double()>'到'bool'
bool yes = (f = the_answer);
^ ~~~~~~~~~~~~~~~~
1错误生成。
EDIT 我没有看到
关键字..没有隐式转换,我想我必须使用 static_cast
。
bool yes(f = the_answer);
但是,我假设它真的用于上下文转换表达式用作条件,最常用于 if
语句。与隐式转换不同,上下文转换可以调用显式
构造函数和转换函数。
//这很好(虽然编译器可能警告)
pre>
if(f = the_answer){
// ...
}
The C++11
std::function
is supposed to implementoperator 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 usestatic_cast
.解决方案
operator bool()
forstd::function
isexplicit
, 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 callexplicit
constructors and conversion functions, unlike implicit conversion.// this is fine (although compiler might warn) if (f = the_answer) { // ... }
这篇关于从std :: function到bool没有可行的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!