Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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, >

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

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

like image 943
Huhwha Avatar asked Sep 29 '13 14:09

Huhwha


1 Answers

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

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; 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:

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

or not bother with bind at all:

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

or use a lambda:

auto future = async(launch::async, []{return a.add(1,2);});
like image 98
Mike Seymour Avatar answered Sep 30 '22 14:09

Mike Seymour