gpt4 book ai didi

c++ - 在 C++11 中使用模板元编程连接列表

转载 作者:行者123 更新时间:2023-12-03 10:05:18 25 4
gpt4 key购买 nike

我创建了一个名为 IntList 的新类型,它表示一个整数列表。这是通过使用模板制作的:

template<int...>
struct IntList;

template<int h, int... t>
struct IntList<h, t...>{
constexpr static int head = h;
typedef IntList<t...> next;
constexpr static int size = sizeof...(t) + 1;
constexpr static bool empty = false;
};

template<>
struct IntList<>{
constexpr static int size = 0;
constexpr static bool empty = true;
};
例如, IntList<1,2,3,4> 是 4 个元素的列表 - 1,2,3,4。
IntList<1,2,3,4>::head; //Should be 1
IntList<1,2,3,4>::size; //Should be 4
IntList<1,2,3,4>::next; //Should be IntList<2,3,4>
现在,我想使用模板来创建连接这些类型列表的新类型。它将被称为 ConcatedIntLists。
如果我只需要连接两个列表,那么这很简单:
template<typename...>
struct ConcatedIntLists;

template<int...T1, int...T2>
struct ConcatedIntLists<IntList<T1...>, IntList<T2...>>{
typedef IntList<T1..., T2...> list;
};
但是如果我想连接未知数量的列表怎么办?例如:
ConcatedIntLists<IntList<1,2,3>, IntList<>, IntList<4,5>>::list; //Should be IntList<1,2,3,4,5>
ConcatedIntLists<IntList<1>, IntList<2>, IntList<3>, IntList<4>>::list; //Should be IntList<1,2,3,4>
这是我陷入困境的部分。

最佳答案

你可以添加这个额外的特化:

template<int...T1, typename...Ts>
struct ConcatedIntLists<IntList<T1...>, Ts...> {
typedef typename ConcatedIntLists<IntList<T1...>,
typename ConcatedIntLists<Ts...>::list>::list list;
};
Demo .

关于c++ - 在 C++11 中使用模板元编程连接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65855963/

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