jeudi 2 août 2018

Can't call future::get on a future stored in a map

I am storing C++ futures in a map, but then I can't call future::get() on the futures once they are in the map.

Code is:

#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;
}

The compiler error is:

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

I think this has something to do with futures not being callable (eg. see this post and this post), but don't know how to fix it.

Aucun commentaire:

Enregistrer un commentaire