Can std :: async call std :: function objects?

Is it possible to call function objects created using std :: bind using std :: async. The following code does not 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; } 

Error:

There is no corresponding function to call "async": The candidate template is ignored: replacement failed [using Fp = std :: _ 1 :: function &, Args = <>]: there is no type named 'type' in 'std :: _ 1 :: __ invoke_of,>

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

(This compiles using Xcode 5 with the Apple LLVM 5.0 compiler)

+6
source share
1 answer

Is it possible to call function objects created using std::bind using std::async

Yes, you can call any functor if you specified the correct number of arguments.

Am I doing something wrong?

You convert a bound function that takes no arguments to function<int(int,int)> , which takes (and ignores) two arguments; then tries to run it with no arguments.

You can specify the correct signature:

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

or avoid overhead when creating a function :

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

or don't bind at all:

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

or use lambda:

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

Source: https://habr.com/ru/post/954889/


All Articles