微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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);});

原文地址:https://www.jb51.cc/c/114883.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐