Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using async with std::accumulate

I thought this would be simpler but having tried many variations of the following I can't get this code to compile

#include <thread>
#include <algorithm>
#include <future>

int main()
{
    std::vector<int> vec(1000000, 0);
    std::future<int> x = std::async(std::launch::async, std::accumulate, vec.begin(), vec.end(), 0);
}

error: no matching function for call to 'async(std::launch, <unresolved overloaded function type>, std::vector<int>::iterator, std::vector<int>::iterator, int)'

What am I missing?

like image 397
CanISleepYet Avatar asked Jul 26 '26 07:07

CanISleepYet


1 Answers

Because std::accumulate is a template you have to supply the template parameters (to resolve it to a specific function) before taking its address.

#include <thread>
#include <algorithm>
#include <future>
#include <vector>
#include <numeric>

int main()
{
    std::vector<int> vec(1000000, 0);

    std::future<int> x = std::async(std::launch::async,
        &std::accumulate<std::vector<int>::const_iterator, int>,
            vec.begin(), vec.end(), 0);
}

That's kind of yuck so you could use a lambda instead:

std::future<int> x = std::async(std::launch::async,
    [&]{ return std::accumulate(vec.begin(), vec.end(), 0); });
like image 184
Galik Avatar answered Jul 27 '26 20:07

Galik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!