[英]Can std::async call std::function objects?
是否可以使用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編譯器編譯的)
是否可以使用
std::async
調用使用std::bind
創建的函數對象
是的,只要您提供正確數量的參數,就可以調用任何仿函數。
難道我做錯了什么?
您將綁定函數(不帶參數)轉換為function<int(int,int)>
,它接受(並忽略)兩個參數; 然后嘗試在沒有參數的情況下啟動它。
您可以指定正確的簽名:
function<int()> sumFunc = bind(&Adder::add, &a, 1, 2);
或者避免創建function
的開銷:
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);});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.