【问题标题】:Using async with std::accumulate将异步与 std::accumulate 一起使用
【发布时间】:2019-03-16 21:27:19
【问题描述】:

我认为这会更简单,但尝试了以下多种变体后,我无法编译此代码

#include <thread>
#include <algorithm>
#include <future>

int main()
{
    std::vector<int> vec(1000000, 0);
    std::future<int> x = std::async(std::launch::async, std::accumulate, vec.begin(), vec.end(), 0);
}

error: no matching function for call to 'async(std::launch, &lt;unresolved overloaded function type&gt;, std::vector&lt;int&gt;::iterator, std::vector&lt;int&gt;::iterator, int)'

我错过了什么?

【问题讨论】:

  • std::accumulate 是一个模板。无法推断参数类型。需要指定每个。

标签: c++ concurrency


【解决方案1】:

因为std::accumulate 是一个模板,您必须在获取其地址之前提供模板参数(以将其解析为特定函数)。

#include <thread>
#include <algorithm>
#include <future>
#include <vector>
#include <numeric>

int main()
{
    std::vector<int> vec(1000000, 0);

    std::future<int> x = std::async(std::launch::async,
        &std::accumulate<std::vector<int>::const_iterator, int>,
            vec.begin(), vec.end(), 0);
}

这有点糟糕,所以你可以使用 lambda 代替:

std::future<int> x = std::async(std::launch::async,
    [&]{ return std::accumulate(vec.begin(), vec.end(), 0); });

【讨论】:

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