vendredi 22 janvier 2021

Concatenating lists using template metaprogramming in C++11

I've created a new type called IntList, which represents a list of integers. This was made by using templates:

template<int...>
struct IntList;

template<int h, int... t>
struct IntList<h, t...>{
    constexpr static int head = h;
    typedef IntList<t...> next;
    constexpr static int size = sizeof...(t) + 1;
    constexpr static bool empty = false;
};

template<>
struct IntList<>{
    constexpr static int size = 0;
    constexpr static bool empty = true;
};

For example, IntList<1,2,3,4> is a list of 4 elements - 1,2,3,4.

IntList<1,2,3,4>::head; //Should be 1
IntList<1,2,3,4>::size; //Should be 4
IntList<1,2,3,4>::next; //Should be IntList<2,3,4>

Now, I want to use templates to create a new type which concatenates these type of lists. It will be called ConcatedIntLists. If I need to concatenate only two lists, then it is pretty simple:

template<typename...>
struct ConcatedIntLists;

template<int...T1, int...T2>
struct ConcatedIntLists<IntList<T1...>, IntList<T2...>>{
    typedef IntList<T1..., T2...> list;
};

But what if I want to concatenate unknown number of lists? For example:

ConcatedIntLists<IntList<1,2,3>, IntList<>, IntList<4,5>>::list; //Should be IntList<1,2,3,4,5>
ConcatedIntLists<IntList<1>, IntList<2>, IntList<3>, IntList<4>>::list; //Should be IntList<1,2,3,4>

This is the part I got stuck in.

Aucun commentaire:

Enregistrer un commentaire