gpt4 book ai didi

c++ - c++ - 如何在C++中使用匹配数据类型的两对中的四个元素构造一个元组?

转载 作者:行者123 更新时间:2023-12-04 11:47:03 25 4
gpt4 key购买 nike

我有一个功能 f() ,返回 std::pair<A, B>某些类型 AB .我还有另一个功能 g() ,那叫 f()两次并返回 std::tuple<A, B, A, B> .有没有办法构造返回tuple直接从两个电话拨打 f() ?所以我想将当前代码的最后三行作为快捷方式:

std::tuple<A, B, A, B>
g(type1 arg1, type2 arg2, ...) {
// perform some preprocessing
auto pair1 = f(...);
auto pair2 = f(...);
return { pair1.first, pair1.second, pair2.first, pair2.second }
}
成一个类轮(而不是三个)。如果该解决方案也适用于任意长度的元组,那就太好了,尤其是在模板情况下。
例如,在当前的 Python3 中,解决方案是 return (*f(...), *f(...)) . C++ 中是否有与 Python 中类似的列表/元组解包运算符?

最佳答案

是的,有 std::tuple_cat .即使 cppreference 说...

The behavior is undefined if any type in [arguments] is not a specialization of std::tuple. However, an implementation may choose to support types (such as std::array and std::pair) that follow the tuple-like protocol.


我已经对其进行了测试,并且所有主要的标准库实现(libstdc++、libc++ 和 MSVC 的库)都支持它。
例子:
#include <tuple>

struct A {};
struct B {};

std::pair<A, B> foo() {return {};}

std::tuple<A, B, A, B> bar()
{
return std::tuple_cat(foo(), foo());
}

关于c++ - c++ - 如何在C++中使用匹配数据类型的两对中的四个元素构造一个元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68822047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com