1. 计算Typelist长度
template struct Length;
template <> struct Length
{
enum { value = 0 };
};
template
struct Length< Typelist >
{
enum { value = 1 + Length::value };
};
2. 以索引方式访问Typelist的某个元素
template struct TypeAt;
template
struct TypeAt , 0>
{
typedef Head Result;
};
template
struct TypeAt , i>
{
typedef typename TypeAt ::Result Result;
};
TypeAt对越界的index访问会编译不通过,TypeAt有一个变型版本TypeAtNonStrict,它对越界的访问返回DefaultType
template
struct TypeAtNonStrict
{
typedef DefaultType Result;
};
template
struct TypeAtNonStrict , 0, DefaultType>
{
typedef Head Result;
};
template
struct TypeAtNonStrict , i, DefaultType>
{
typedef typename
TypeAtNonStrict ::Result Result;
};
3. 查找一个Type
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) };
};
这篇列了Typelist上的三种操作:计算长度、访问INDEX对应的Type、查找一个Type;它们都使用了"recursive templates","recursive templates"和函数递归很相似,它用来引导编译器推导,实现的极为优雅。