【问题标题】:Generic implementation to get size of typelist获取类型列表大小的通用实现
【发布时间】: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


    【解决方案1】:

    您可以在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... 获取模板参数的大小,不需要模板递归。

    LIVE

    【讨论】:

    • 那很好。不知道为什么我不必要地使用了太多参数。
    猜你喜欢
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多