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

是否可以使用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&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...