typetraits using TypeList

After Modern C++ Design

#include

#define TYPELIST_1(T1) TypeList
#define TYPELIST_2(T1, T2) TypeList< T1, TYPELIST_1(T2) >
#define TYPELIST_3(T1, T2, T3) TypeList< T1, TYPELIST_2(T2, T3) >
#define TYPELIST_4(T1, T2, T3, T4) TypeList< T1, TYPELIST_3(T2, T3, T4) >
#define TYPELIST_5(T1, T2, T3, T4, T5) TypeList< T1, TYPELIST_4(T2, T3, T4, T5) >

using namespace std;

// Mark the end of list
struct NullType { };

// TypeList Definition
template
struct TypeList
{
typedef T Head;
typedef U Tail;
};

// General IndexOf operator Definition
template
struct IndexOf;

// If the given list is NullType, then return -1
template
struct IndexOf
{
enum { value = -1 };
};

// Head is the type we’re looking for
template
struct IndexOf, Head>
{
enum { value = 0 };
};

// Neither Head nor Tail is T.
// Recursively search for T in the Tail which is either TypeList or
// NullType
template
struct IndexOf, T>
{
private:
enum { temp = IndexOf::value };

public:
enum { value = temp == -1 ? -1 : 1 + temp };
};

// TypeTraits using TypeList
template
class TypeTraits
{
private:
// List of Numbers
typedef TYPELIST_5(int, short, long, float, double) numbers;

public:
// Search for given type T in the list
enum { isNumber = IndexOf::value >= 0 };
};

int main()
{
cout << "int is " << (TypeTraits::isNumber ? “a number type.” : “not a number type.”) << endl; cout << "string is " << (TypeTraits::isNumber ? “a number type.” : “not a number type.”) << endl; return EXIT_SUCCESS; } [/code]

Similar Posts:

Comments 2

  1. Marc wrote:

    Modern C++ Design is a mind-bending book!

    Posted 16 Jun 2006 at 11:38 pm
  2. MKSeo wrote:

    Hi Marc. Yes, Modern C++ Design is a MUST READ!

    Posted 17 Jun 2006 at 1:36 pm

Post a Comment

Your email is never published nor shared.