[英]Can std::async call std::function objects?
Is it possible to call function objects created with std::bind using std::async. 是否可以使用std :: async调用使用std :: bind创建的函数对象。 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;
}
The error is: 错误是:
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, > 没有用于调用'async'的匹配函数:忽略候选模板:替换失败[使用Fp = std :: _1 :: function&, Args = <>]:'std :: _1 :: __ invoke_of中没有名为'type'的类型 ,>
Is it just not possible to use async with std::function objects or am I doing something wrong? 是不是可以与std :: function对象使用异步,或者我做错了什么?
(This is being compiled using Xcode 5 with the Apple LLVM 5.0 compiler) (这是使用Xcode 5和Apple LLVM 5.0编译器编译的)
Is it possible to call function objects created with
std::bind
usingstd::async
是否可以使用
std::async
调用使用std::bind
创建的函数对象
Yes, you can call any functor, as long as you provide the right number of arguments. 是的,只要您提供正确数量的参数,就可以调用任何仿函数。
am I doing something wrong?
难道我做错了什么?
You're converting the bound function, which takes no arguments, to a function<int(int,int)>
, which takes (and ignores) two arguments; 您将绑定函数(不带参数)转换为
function<int(int,int)>
,它接受(并忽略)两个参数; then trying to launch that with no arguments. 然后尝试在没有参数的情况下启动它。
You could specify the correct signature: 您可以指定正确的签名:
function<int()> sumFunc = bind(&Adder::add, &a, 1, 2);
or avoid the overhead of creating a function
: 或者避免创建
function
的开销:
auto sumFunc = bind(&Adder::add, &a, 1, 2);
or not bother with bind
at all: 或根本不打扰
bind
:
auto future = async(launch::async, &Adder::add, &a, 1, 2);
or use a lambda: 或者使用lambda:
auto future = async(launch::async, []{return a.add(1,2);});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.