从std :: function到bool没有可行的转换 [英] No viable conversion from std::function to bool

查看:672
本文介绍了从std :: function到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

c> c> c> c> code> explicit ,因此它不能用于复制初始化。你可以直接初始化:

  bool yes(f = the_answer); 

但是,我假设它真的用于上下文转换表达式用作条件,最常用于 if 语句。与隐式转换不同,上下文转换可以调用显式构造函数和转换函数。

  //这很好(虽然编译器可能警告)
if(f = the_answer){
// ...
}
pre>

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.

解决方案

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) {
    // ...
}

这篇关于从std :: function到bool没有可行的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆