std :: async可以调用std :: function对象吗? [英] Can std::async call std::function objects?

查看:142
本文介绍了std :: async可以调用std :: function对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用std :: async调用使用std :: bind创建的函数对象。以下代码无法编译:

Is it possible to call function objects created with std::bind using std::async. The following code fails to compile:

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

错误是:

没有用于调用异步的匹配函数:
候选模板被忽略:替换失败[with Fp = std :: _1 :: function& ;, Args =< ;>]:'std :: _1 :: __ invoke_of中没有名为'type'的类型,>

No matching function for call to 'async': Candidate template ignored: substitution failure [with Fp = std::_1::function &, Args = <>]: no type named 'type' in 'std::_1::__invoke_of, >

是否不可能在std中使用异步:: function对象还是我做错了什么?

Is it just not possible to use async with std::function objects or am I doing something wrong?

(正在使用Xcode 5和Apple LLVM 5.0编译器进行编译)

(This is being compiled using Xcode 5 with the Apple LLVM 5.0 compiler)

推荐答案


是否可以使用以下方法调用使用 std :: bind 创建的函数对象 std :: async

是的,您可以调用任何仿函数,只要

Yes, you can call any functor, as long as you provide the right number of arguments.


我做错了吗?

am I doing something wrong?

您正在将不带参数的绑定函数转换为 function< int(int,int)> ,它接受(并忽略)两个参数;

You're converting the bound function, which takes no arguments, to a function<int(int,int)>, which takes (and ignores) two arguments; then trying to launch that with no arguments.

您可以指定正确的签名:

You could specify the correct signature:

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

或避免创建函数的开销

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

或根本不用 bind 打扰:

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

或使用lambda:

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

这篇关于std :: async可以调用std :: function对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆