无法对存储在地图中的未来调用 future::get
Can't call future::get on a future stored in a map
我正在将 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()
我认为这与期货不可调用有关(例如,请参阅此 and this post),但不知道如何解决。
问题是您在迭代地图时使用 const-iterator,那么您只能读取地图的值(您可以调用 const future
上的成员)。但是你在未来的对象上调用 get
,你会得到错误,因为 get
是 future
class 的非常量限定成员。所以试试
for (auto it = tasks.begin(); it != tasks.end(); ) {
我正在将 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()
我认为这与期货不可调用有关(例如,请参阅此
问题是您在迭代地图时使用 const-iterator,那么您只能读取地图的值(您可以调用 const future
上的成员)。但是你在未来的对象上调用 get
,你会得到错误,因为 get
是 future
class 的非常量限定成员。所以试试
for (auto it = tasks.begin(); it != tasks.end(); ) {