3

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.

1 Answers1

2

The problem seems to be that you have both a data member and a member function named calc. Renaming one solves the issue.

[Live example]

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
  • Thanks for your input, it resolves the issue in this sample code. But I am facing an issue with a piece of code: `auto handle = std::async(&CTest::maxAvgCalc_task, this, std::ref(pFrameIn), 0, pFrameIn->height*pFrameIn->width); auto asyncTuple = handle.get();` Here the `handle.get` is returning function pointer instead of tuple. Hence `get<0>(asyncTuple)` is giving an error 'No instance of overloaded function 'std::get' matches the argument list' – Peter Abraham May 08 '18 at 11:31
  • @PeterAbraham I can hardly help with code I cannot see. Please create a [mcve] which will reproduce the *actual* error you're getting, and post that. – Angew is no longer proud of SO May 08 '18 at 12:17
  • @PeterAbraham As this problem (you posted) is solved, place a checkmark next to the answer that solved your problem. If fixing this problem revealed another problem, use the [Ask Question] button to ask about that new problem. Make sure the new question is also a [mcve]. Comments are not suited for question extensions/follow up questions. – Yakk - Adam Nevraumont May 08 '18 at 17:16