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

What is the correct way of calling a template function using std::async

本文关键字:方法 是什么 async std 调用 使用 函数      更新时间:2023-10-16

我试图了解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:"std::async":找不到匹配的重载函数

为什么我会收到此错误?如何修复?

您应该使用 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);