mercredi 26 juin 2019

How to use a range-based for loop with a vector of future

I have a program that calculates some values in different threads with std::packaged_task<int()>. I store the std::future I get from the packaged tasks via get_future() in a vector (defined as std::vector<std::future<int>>).

When I calculate the sum of all the tasks I use a for loop and it's working:

// set up of the tasks
std::vector<std::future<int>> results;
// store the futures in results
// each task execute in its own thread

int sum{ 0 };
for (auto i = 0; i < results.size; ++i) {
    sum += results[i].get();
}

But I would rather use a range-based for loop:

// set up of the tasks
std::vector<std::future<int>> results;
// store the futures in results
// each task execute in its own thread

int sum{ 0 };
for (const auto& result : results) {
    sum += result.get();
}

Currently I get a compile error with clang:

program.cxx:83:16: error: 'this' argument to member function 'get' has type 'const std::function<int>', but function is not marked const

       sum += result.get();
              ^~~~~~
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/9.1.0/../../../../include/c++/9.1.0/future:793:7: note: 'get' declared here

       get()
       ^

Is it possible to use Range-based for loop with a vector of future<int>?

Aucun commentaire:

Enregistrer un commentaire