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

  • A+
Category:Languages

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?


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: