TypeList 是一個**編譯時**的類型序列容器,不包含數值,僅攜帶類型信息。結構定義:
template
struct TypeList {
typedef Head Head;
typedef Tail Tail;
};
struct NullType {}; // 終結符
便於聲明多類型列表:
#define TYPELIST_1(T1) TypeList
#define TYPELIST_2(T1,T2) TypeList
#define TYPELIST_3(T1,T2,T3) TypeList
// ... 以此類推
template struct Length;
template <> struct Length { enum { value = 0 }; };
template
struct Length> {
enum { value = 1 + Length::value };
};
template struct TypeAt;
template
struct TypeAt, 0> { typedef Head Result; };
template
struct TypeAt, i> {
typedef typename TypeAt::Result Result;
};
template
struct TypeAtNonStrict { typedef DefaultType Result; };
// ... 偏特化實現
template struct IndexOf;
template struct IndexOf { enum { value = -1 }; };
template
struct IndexOf, T> { enum { value = 0 }; };
template
struct IndexOf, T> {
private:
enum { temp = IndexOf::value };
public:
enum { value = temp == -1 ? -1 : 1 + temp };
};
template struct Append;
// ... 多種偏特化處理 NullType、單類型、TypeList 等情況
template struct Reverse;
template <> struct Reverse { typedef NullType Result; };
template
struct Reverse> {
typedef typename Append::Result, Head>::Result Result;
};
typedef TYPELIST_3(char, int, double) TL3;
static_assert(Length::value == 3);
static_assert(std::is_same::Result, int>::value);
static_assert(IndexOf::value == 2);
typedef Append::Result TL4; // char, int, double, float
static_assert(Length::value == 4);