如何从 std::async 任务返回 std::tuple
How to return std::tuple from a std::async task
如何启动成员函数作为 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
的成员函数。重命名一个可以解决问题。
[现场示例]
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 如何获取std::result_of函数的返回类型
- 架构决策:返回std::future还是提供回调
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 使用std::mt19937从字符串中返回一个随机单词
- 如何使用std::min和std::less返回对象
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- 返回一个带有 std::move 的对象并链接函数
- 推导 std::vector::back() 的返回类型
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?
- 如何从 std::thread 返回值
- 从 std<Derived>::shared_ptr 的向量返回 std::shared_ptr<Base>
- 在带有尾部斜杠的路径上返回 std::filesystem::create_directories() 的值
- std::find,返回所有找到的值的替代方法,而不仅仅是存在重复的向量的第一个值
- 如何从 std::vector 搜索和返回项目
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 我无法使用C++指针指向类方法返回的 std::vector
- 如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?
- 使用 std::p air 进行返回值优化
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?