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

此生再无相见时 提交于 2020-02-21 11:55:35

问题


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)


回答1:


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


来源:https://stackoverflow.com/questions/19079179/can-stdasync-call-stdfunction-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!