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

c – std :: async可以调用std :: function对象吗?,第1张

概述是否可以使用std :: async调用使用std :: bind创建的函数对象.以下代码无法编译: #include <iostream>#include <future>#include <functional>using namespace std;class Adder {public: int add(int x, int y) { return x 是否可以使用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);});
总结

以上是内存溢出为你收集整理的c – std :: async可以调用std :: function对象吗?全部内容,希望文章能够帮你解决c – std :: async可以调用std :: function对象吗?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1246400.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存