1.Length
template <class T, class U>
struct Typelist
{
typedef T Head;
typedef U Tail;
};
class NullType {};
template <class TList> struct Length;
//特化
template <> struct Length<NullType>
{
enum { value = 0 };
};
//递归式
template <class T, class U>
struct Length< Typelist<T, U> >
{
enum { value = 1 + Length<U>::value };
};
#define LOKI_TYPELIST_1(T1) Typelist<T1, NullType>
#define LOKI_TYPELIST_2(T1, T2) Typelist<T1, LOKI_TYPELIST_1(T2) >
#define LOKI_TYPELIST_3(T1, T2, T3) Typelist<T1, LOKI_TYPELIST_2(T2, T3) >
int main()
{
//3
std::size_t n=Length<LOKI_TYPELIST_3(int,int,int)>::value;
}
2.typedef typename的定义
见此
template <class TList, unsigned int index> struct TypeAt;
template <class Head, class Tail>
struct TypeAt<Typelist<Head, Tail>, 0>
{
typedef Head Result;
};
template <class Head, class Tail, unsigned int i>
struct TypeAt<Typelist<Head, Tail>, i>
{
typedef typename TypeAt<Tail, i - 1>::Result Result;
};
http://blog.163.com/cp7618@yeah/blog/static/70234777201122111034365/
http://www.cnblogs.com/carekee/articles/1748675.html
typename告诉编译器, 后面的消息XXX::type是一个已经存在于某处的类型的名字(type name)
3.TypeAtNonStrict
加了一个默认值DefaultType
template <class TList, unsigned int index,
typename DefaultType = NullType>
struct TypeAtNonStrict
{
typedef DefaultType Result;
};
template <class Head, class Tail, typename DefaultType>
struct TypeAtNonStrict<Typelist<Head, Tail>, 0, DefaultType>
{
typedef Head Result;
};
template <class Head, class Tail, unsigned int i, typename DefaultType>
struct TypeAtNonStrict<Typelist<Head, Tail>, i, DefaultType>
{
typedef typename
TypeAtNonStrict<Tail, i - 1, DefaultType>::Result Result;
};
4.IndexOf
也是递归式,定义了一个temp临时变量
template <class TList, class T> struct IndexOf;
template <class T>
struct IndexOf<NullType, T>
{
enum { value = -1 };
};
template <class T, class Tail>
struct IndexOf<Typelist<T, Tail>, T>
{
enum { value = 0 };
};
template <class Head, class Tail, class T>
struct IndexOf<Typelist<Head, Tail>, T>
{
private:
enum { temp = IndexOf<Tail, T>::value };
public:
enum { value = (temp == -1 ? -1 : 1 + temp) };
};
5.Append
6.Erase