vendredi 27 mars 2020

Generic implementation to get size of typelist

How to implement generic SizeOfT template for typelists? I'm learning C++ template metaprogramming, decided to implement SizeOfT template to get the number of types a typelist contain. I came up with following code.

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;
}

Everything works fine in the above code. However, I would like to make SizeOfT more generic so that if new typelist TypeList3 is added, I don't need to provide any specialization for that.

I'm using a C++11 conformant compiler.

Aucun commentaire:

Enregistrer un commentaire