[英]How to use a range-based for loop with a vector of future<T>
我有一个程序,可以使用std::packaged_task<int()>
在不同的线程中计算一些值。 我将从打包任务中通过get_future()
获得的std::future
存储在一个向量中(定义为std::vector<std::future<int>>
)。
当我计算所有任务的总和时,我使用了for循环,它正在工作:
// 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();
}
但是我宁愿使用基于范围的for循环:
// 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();
}
目前,我收到了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()
^
是否可以将基于范围的for循环与future<int>
的vector
一起使用?
您需要从for (const auto& result : results)
删除const
。 std::future
没有提供get
的const限定版本,这是编译器试图调用的版本,因为result
是对const std::future
的引用。
for (auto& result : results) {
sum += result.get();
}
做你想要的。
get
不是const
,因此您需要非const引用:
for (auto& result : results) {
sum += result.get();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.