【问题标题】:Can std::async call std::function objects?std::async 可以调用 std::function 对象吗?
【发布时间】:2013-09-29 14:28:48
【问题描述】:

是否可以使用 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;
}

错误是:

对“异步”的调用没有匹配的函数: 候选模板被忽略:替换失败 [with Fp = std::_1::function &, Args = ]: no type named 'type' in 'std:: _1::__invoke_of,>

是不能对 std::function 对象使用异步还是我做错了什么?

(这是使用 Xcode 5 和 Apple LLVM 5.0 编译器编译的)

【问题讨论】:

  • async 从哪里得到函子参数?尝试传递std::function&lt;void()&gt;。

标签: c++ c++11 std-function stdasync


【解决方案1】:

是否可以使用std::async 调用使用std::bind 创建的函数对象

是的,您可以调用任何函子,只要您提供正确数量的参数。

我做错了吗?

您正在将不带参数的绑定函数转换为带(并忽略)两个参数的function&lt;int(int,int)&gt;;然后尝试在没有参数的情况下启动它。

您可以指定正确的签名:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多