无法调用Future ::获取存储在地图中的Future

时间:2018-08-03 06:53:04

标签: c++ c++11 future

我将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()

我认为这与无法赎回期货有关(例如,见此post和此post),但不知道如何解决。

1 个答案:

答案 0 :(得分:8)

问题在于,您在迭代地图时使用了 const-iterator ,然后您只能读取地图的值(可以在{{1上调用 const }})。但是您在将来的对象上调用future,并且由于getget类的非常量限定成员而收到错误。因此,尝试

future