【问题标题】:No viable conversion from std::function to bool没有从 std::function 到 bool 的可行转换
【发布时间】: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

【问题讨论】:

标签: c++ c++11 operator-overloading implicit-conversion


【解决方案1】:

operator bool() for std::functionexplicit,因此它不能用于复制初始化。您实际上可以进行直接初始化:

bool yes(f = the_answer);

但是,我认为它确实适用于上下文转换,当表达式用作条件时会发生这种情况,最常见的是if 语句。上下文转换可以调用explicit构造函数和转换函数,不像隐式转换。

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

【讨论】:

  • 干杯,我想在 bool Foo::check() const { return m_function; } 这样的方法中使用隐式转换。对我来说太糟糕了:)
  • @Sh3ljohn:如果你真的想避免显式转换,你可以写成bool Foo::check() const { return m_function ? true : false; }
  • @ChrisDodd return !!m_function;.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 2020-09-08
  • 2015-08-25
  • 1970-01-01
相关资源
最近更新 更多