What is the correct way to call a template function using std :: async

I am trying to understand usage std::async. I wrote below a template function to accumulate all the records in an integrated array.

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

When I call the function above in main, I get below compilation errors (along with several):

error C2672: 'std :: async': the corresponding overloaded function was not found

Why am I getting this error? How can this be fixed?

+4
source share
1 answer

You must use std::refto save reference semantics.

Change line:

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

at

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

Source: https://habr.com/ru/post/1696355/


All Articles