【发布时间】:2021-04-27 13:23:39
【问题描述】:
我创建了一个名为 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 是 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>
这是我陷入的部分。
【问题讨论】:
-
为什么两个 IntList 的串联不能简单地成为另一个 IntList?
-
@NathanPierson 你可以通过在末尾写“::list”来提取它。
标签: c++ c++11 templates template-meta-programming