Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to understand the uses of std::async. I wrote below template function to accumulate all the entries in an integral 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 above function in main I get below compilation error (along with some more):

error C2672: 'std::async': no matching overloaded function found

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

like image 298
Sajal Avatar asked Dec 08 '22 15:12

Sajal


1 Answers

You should use std::ref to preserve reference semantics.

Change is line:

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

to:

auto res1 = std::async(std::launch::async, parallel_sum<T, N>, std::ref(arr), start, mid);
like image 108
llllllllll Avatar answered Dec 10 '22 06:12

llllllllll