mardi 8 mai 2018

How to return std::tuple from a std::async task

How can I launch a member function as a std::async task, which returns a std::tuple.

Sample code:

#include <iostream>
#include <future>
#include <tuple>
#include <numeric>


class Foo {
    bool calc;
public:
    Foo(bool b) : calc(b) 
    {}

    std::tuple<long, double> calc(std::vector<int> a) {
        long sum = 0;
        double avg = 0.0;

        if ((*this).calc) {
            long sum = std::accumulate(a.begin(), a.end(), 0);
            double avg = sum / a.size();
        }
        return std::make_tuple(sum, avg);
    }

    void call_calc(std::vector<int> i) {

        auto handle = std::async(&Foo::calc, this, i);
        auto resultTuple = handle.get();

        std::cout << "Sum = " << std::get<0>(resultTuple) << "  Average = " << std::get<1>(resultTuple) << std::endl;
    }
};

int main() {
    std::vector<int> a{ 2, 5, 6, 7, 3 };
    Foo foo(true);
    foo.call_calc(a);
}

In this example, without the member variable, code works fine. The above code is throwing compilation error for following lines:

auto handle = std::async(&Foo::calc, this, i);

Error: No instance of overloaded function 'std::async' matches the argument list.

std::cout << "Sum = " << std::get<0>(resultTuple) << "  Average = " << std::get<1>(resultTuple) << std::endl;

Error: No instance of overloaded function 'std::get' matches the argument list.

Aucun commentaire:

Enregistrer un commentaire