[英]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.