Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 461
dvep Avatar asked Jan 24 '23 12:01

dvep


1 Answers

You might add this extra specialization:

template<int...T1, typename...Ts>
struct ConcatedIntLists<IntList<T1...>, Ts...> {
    typedef typename ConcatedIntLists<IntList<T1...>,
                                      typename ConcatedIntLists<Ts...>::list>::list list;
};

Demo.

like image 100
Artemy Vysotsky Avatar answered Jan 30 '23 12:01

Artemy Vysotsky