Huh*_*wha 7 c++ c++11 std-function stdasync
是否可以使用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;
}
Run Code Online (Sandbox Code Playgroud)
错误是:
没有用于调用'async'的匹配函数:忽略候选模板:替换失败[使用Fp = std :: _1 :: function&,Args = <>]:'std :: _1 :: __ invoke_of中没有名为'type'的类型,>
是不是可以与std :: function对象使用异步,或者我做错了什么?
(这是使用Xcode 5和Apple LLVM 5.0编译器编译的)
Mik*_*our 13
是否可以调用
std::bind使用using 创建的函数对象std::async
是的,只要您提供正确数量的参数,就可以调用任何仿函数.
难道我做错了什么?
你将绑定函数(不带参数)转换为a function<int(int,int)>,它接受(并忽略)两个参数; 然后尝试在没有参数的情况下启动它.
您可以指定正确的签名:
function<int()> sumFunc = bind(&Adder::add, &a, 1, 2);
Run Code Online (Sandbox Code Playgroud)
或避免创建一个function:
auto sumFunc = bind(&Adder::add, &a, 1, 2);
Run Code Online (Sandbox Code Playgroud)
或根本不打扰bind:
auto future = async(launch::async, &Adder::add, &a, 1, 2);
Run Code Online (Sandbox Code Playgroud)
或者使用lambda:
auto future = async(launch::async, []{return a.add(1,2);});
Run Code Online (Sandbox Code Playgroud)