【发布时间】:2020-07-07 23:18:23
【问题描述】:
如何为类型列表实现通用SizeOfT 模板?我正在学习 C++ 模板元编程,决定实现 SizeOfT 模板来获取类型列表包含的类型数量。我想出了以下代码。
template <typename... Ts>
struct TypeList1;
template <typename... Ts>
struct TypeList2;
template <typename H, typename... Ts>
struct SizeOfT;
// Specialized for TypeList1
template <typename H, typename... Ts>
struct SizeOfT <TypeList1<H, Ts...>> {
constexpr static auto value = 1 + sizeof...(Ts);
};
template <>
struct SizeOfT <TypeList1<>> {
constexpr static auto value = 0;
};
// Specialized for TypeList2, works fine but
// it would be less code if generic SizeOfT can be implemented which can handle
// both TypeList1 and TypeList2 and maybe any future TypeList3 and so on...
template <typename H, typename... Ts>
struct SizeOfT <TypeList2<H, Ts...>> {
constexpr static auto value = 1 + sizeof...(Ts);
};
template <>
struct SizeOfT <TypeList2<>> {
constexpr static auto value = 0;
};
int main() {
using tl1 = TypeList1<int, char, bool>;
using tl2 = TypeList2<float, double>;
static_assert(SizeOfT<tl1>::value == 3, "tl1 size is not 3");
static_assert(SizeOfT<tl2>::value == 2, "tl2 size is not 2");
return 0;
}
上面的代码一切正常。但是,我想让SizeOfT 更通用,这样如果添加了新类型列表TypeList3,我就不需要为此提供任何专业化。
我正在使用符合 C++11 的编译器。
【问题讨论】:
标签: c++ c++11 templates metaprogramming template-meta-programming