无法召唤未来::获取存储在地图中的未来

Joh*_*ohn 0 c++ future c++11

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

我认为这与期货不可调用有关(例如,看到这篇文章和这篇文章),但不知道如何解决它.

raf*_*x07 8

问题是你在迭代地图时使用const-iterator,那么你只能读取map的值(你可以调用const memebers future).但是你正在调用get未来的对象,并且因为get是非const限定的future类成员而得到错误.所以试试吧

for (auto it = tasks.begin(); it != tasks.end(); ) {
Run Code Online (Sandbox Code Playgroud)