如何实现泛型
SizeOfT
排版模板?我正在学习C++模板元编程,决定实现
尺寸英尺
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;
}
在上面的代码中,一切正常。但是,我想
更通用,这样如果新的类型列表
TypeList3
是的,我不需要为此提供任何专门化。
我使用的是C++ 11兼容编译器。