1

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>?

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
ByteNudger
  • 1,545
  • 5
  • 29
  • 37

2 Answers2

5

You need to remove the const from for (const auto& result : results). std::future does not provide a const qualified version of get which is what the compiler is trying to call since result is a reference to a const std::future.

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

Does what you want.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
4

getis not const, so you need non-const references:

for (auto& result : results) {
    sum += result.get();
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302