我将C++期货存储在地图中,但是future::get()一旦它们出现在地图中,我就无法调用期货.
代码是:
#include <iostream>
#include <map>
#include <cstdlib>
#include <future>
using namespace std;
int my_func(int x) {
return x;
}
int main()
{
map<int, future<int>> tasks;
// Create a task and add it to the map
int job_no = 0;
tasks.insert(make_pair(job_no, async(&my_func, job_no)) );
// See if the job has finished
for (auto it = tasks.cbegin(); it != tasks.cend(); ) {
auto job = it->first;
auto status = (it->second).wait_for(chrono::seconds(5));
if (status == future_status::ready) {
int val = (it->second).get(); /* This won't compile */
cout << "Job " << job << " has finished with value: " << val << "\n";
it = tasks.erase(it);
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器错误是:
test.cc:26:39: error: passing ‘const std::future<int>’ as ‘this’ argument discards qualifiers [-fpermissive]
int val = (it->second).get(); /* This won't compile */
^
In file included from test.cc:4:0:
/usr/include/c++/7/future:793:7: note: in call to ‘_Res std::future<_Res>::get() [with _Res = int]’
get()
Run Code Online (Sandbox Code Playgroud)
问题是你在迭代地图时使用const-iterator,那么你只能读取map的值(你可以调用const memebers future).但是你正在调用get未来的对象,并且因为get是非const限定的future类成员而得到错误.所以试试吧
for (auto it = tasks.begin(); it != tasks.end(); ) {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
141 次 |
| 最近记录: |