Can std::async call std::function objects?
Asked Answered
C

1

7

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)

Commutator answered 29/9, 2013 at 14:28 Comment(1)
where would async get the functor arguments from? Try passing an std::function<void()>.Luzluzader
F
14

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);});
Francium answered 29/9, 2013 at 14:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.