使用std :: async调用模板函数的正确方法是什么

时间:2018-04-20 11:38:48

标签: c++ c++11 templates

我想了解std::async的用法。我在下面写了模板函数来累积整数数组中的所有条目。

template<typename T, int N, typename = std::enable_if<std::is_integral<T>::value>::type>
T parallel_sum(T(&arr)[N], size_t start = 0, size_t end = N - 1) {
    if (end - start < 1000) {
        return std::accumulate(std::begin(arr) + start, std::begin(arr) + end + 1, 0);
    }
    else {
        size_t mid = start + (end - start) / 2;
        auto res1 = std::async(std::launch::async, parallel_sum<T, N>, arr, start, mid);
        auto res2 = parallel_sum(arr, mid + 1, end);
        return res2 + res1.get();
    }
}

当我在main中调用上面的函数时,我得到以下编译错误(以及更多):

  

错误C2672:&#39; std :: async&#39;:找不到匹配的重载函数

为什么我收到此错误?如何解决?

1 个答案:

答案 0 :(得分:14)

您应该使用std::ref来保留引用语义。

更改为行:

auto res1 = std::async(std::launch::async, parallel_sum<T, N>, arr, start, mid);

为:

auto res1 = std::async(std::launch::async, parallel_sum<T, N>, std::ref(arr), start, mid);