加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – std :: async可以调用std :: function对象吗?

发布时间:2020-12-16 05:21:08 所属栏目:百科 来源:网络整理
导读:是否可以使用std :: async调用使用std :: bind创建的函数对象.以下代码无法编译: #include iostream#include future#include functionalusing namespace std;class Adder {public: int add(int x,int y) { return x + y; }};int main(int argc,const char *
是否可以使用std :: async调用使用std :: bind创建的函数对象.以下代码无法编译:
#include <iostream>
#include <future>
#include <functional>

using namespace std;

class Adder {
public:
    int add(int x,int y) {
        return x + y;
    }
};

int main(int argc,const char * argv[])
{
    Adder a;
    function<int(int,int)> sumFunc = bind(&Adder::add,&a,1,2);
    auto future = async(launch::async,sumFunc); // ERROR HERE
    cout << future.get();
    return 0;
}

错误是:

没有用于调用’async’的匹配函数:
候选模板被忽略:替换失败[使用Fp = std :: _ 1 :: function&,Args =<>]:’std :: _ 1 :: __ invoke_of,>中没有名为’type’的类型

是不是可以与std :: function对象使用异步,或者我做错了什么?

(这是使用Xcode 5和Apple LLVM 5.0编译器编译的)

解决方法

Is it possible to call function objects created with std::bind using std::async

是的,只要您提供正确数量的参数,就可以调用任何仿函数.

am I doing something wrong?

您将绑定函数(不带参数)转换为函数< int(int,int)>,它接受(并忽略)两个参数;然后尝试在没有参数的情况下启动它.

您可以指定正确的签名:

function<int()> sumFunc = bind(&Adder::add,2);

或者避免创建函数的开销:

auto sumFunc = bind(&Adder::add,2);

或根本不打扰绑定:

auto future = async(launch::async,&Adder::add,2);

或者使用lambda:

auto future = async(launch::async,[]{return a.add(1,2);});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读