From: Marco Costalba (mcostalba_at_[hidden])
Date: 2007-09-01 12:20:54


Form Alexandrescu "Modern C++...", a type list is defined as

template<class T, class U> struct TL {
        typedef T head;
        typedef U tail;
};

A lot of interesting stuff can be made with, please refer to the book
for reference.
A problem is the initialization, as the author says:

"A Plethora of macros that transform recursion into simple enumeration..."

Something like:

#define TL_1(a) TL<a, NullType >
#define TL_2(a,b) TL<a, TL_1(b) >
#define TL_3(a,b,c) TL<a, TL_2(b,c) >
#define TL_4(a,b,c,d) TL<a, TL_3(b,c,d) >
#define TL_5(a,b,c,d,e) TL<a, TL_4(b,c,d,e) >
#define TL_6(a,b,c,d,e,f) TL<a, TL_5(b,c,d,e,f) >

So that it is possible to say: TL_3(int, double, char*) and get the
corresponding type list.

I think it is possible to avoid the macros:

struct E {};
template<class T1 = E, class T2 = E, class T3 = E,
             class T4 = E, class T5 = E, class T6 = E, class T7 = E>
struct TLCreator {
typedef TL<T1, typename TLCreator<T2,T3,T4,T5,T6,T7,E>::MyTL> MyTL;
};
template<> struct TLCreator<E, E, E, E, E, E, E> { typedef E MyTL; };

Now you can say:
        TLCreator<int, double, char*>::MyTL

instead of using a macro.

Following little drivers shows it works.

First define a type list length calculator, as explained by Alexandrescu:

/* type list length */
template<class TL> struct Length;
template<> struct Length<E> { enum{ value = 0 }; };
template<class T, class U> struct Length<TL<T,U> > {
enum{ value = 1 + Length<U>::value };
 };

Then test putting in main() the following

int m1 = Length< TLCreator<int>::MyTL >::value;
int m2 = Length< TLCreator<int, double>::MyTL >::value;
int m3 = Length< TLCreator<int, double, std::string>::MyTL >::value;
int m4 = Length< TLCreator<int, double, std::string, char>::MyTL >::value;

std::cout << "\n" << m1 << ", " << m2 << ", " << m3 << ", " << m4 << "\n";

And you get what you would expect!

I don't know if this is a known result. But it seems very powerful,
indeed you can do a lot of things following the previous schema.

If it is not already known I can post more example of the use of the
above "template parameters iteration" schema.

Thanks for your attention
Marco