如何为打字员实现通用SizeOfT模板?我正在学习C++模板元编程,我决定实现SizeOfT模板来获取一个typelist包含的类型数量。我想出了以下代码。
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的编译器。
发布于 2020-03-27 16:30:01
您可以在template template parameter的帮助下对SizeOfT进行部分专门化。例如:
template <typename H>
struct SizeOfT;
template <template <typename...> class TL, typename... Ts>
struct SizeOfT <TL<Ts...>> {
constexpr static auto value = sizeof...(Ts);
};顺便说一句:你可以直接从sizeof...获取模板参数的大小,而不需要模板递归。
https://stackoverflow.com/questions/60882254
复制相似问题