我将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;
}
编译器错误为:
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()
答案 0 :(得分:8)
问题在于,您在迭代地图时使用了 const-iterator ,然后您只能读取地图的值(可以在{{1上调用 const }})。但是您在将来的对象上调用future
,并且由于get
是get
类的非常量限定成员而收到错误。因此,尝试
future