如何从 std::async 任务返回 std::tuple

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

本文关键字:std 返回 tuple 任务 async      更新时间:2023-10-16

如何启动成员函数作为 std::async 任务,该任务返回 std::tuple。

示例代码:

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

在此示例中,如果没有成员变量,代码可以正常工作。 上面的代码为以下行抛出编译错误:

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

错误:重载函数"std::async"的实例与参数列表不匹配。

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

错误:重载函数"std::get"的实例与参数列表不匹配。

问题似乎是您同时具有数据成员和名为calc的成员函数。重命名一个可以解决问题。

[现场示例]