Field
不从自身继承;相反,template<typename TYPELIST> Field
继承自Field<typename TYPELIST::Tail>
。只要这两个模板参数列表是不同的就可以了。
类型列表是一种陈旧的方法,允许模板(实际上)在将variadic templates添加到该语言之前获取可变数量的类型参数。他们实现了一个简单的单链表结构,相当于LISP cons单元,其中Head
是“有效载荷”类型,其他列表是,它可以是类型列表或TypeListEnd
类型,相当于LISP nil
。
假设我们有
typename TypeList<int, TypeList<char, TypeList<float, TypeListEnd> > > MyTypeList;
在这里,我假设TypeList
是分别对应于它的第一个和第二个模板参数定义Head
和Tail
的typedef成员模板:
template<typename Head, Tail> struct TypeList { typedef Head Head; typedef Tail Tail; };
注意,我因为这可能必须在C++ 03编译器上编译,所以在模板上下文中,>>
总是偶数解释为钻井平台ht移位运算符。
然后你Field
元函数,对MyTypeList
调用时,将业务拓展到
Field<MyTypeList>;
Field<typename TypeList<int, TypeList<char, TypeList<float, TypeListEnd> > > >;
struct Field<...>: TypeList<int, TypeList<char, TypeList<float, TypeListEnd> > >::Tail {
TypeList<int, TypeList<char, TypeList<float, TypeListEnd> > >::Head item;
};
struct Field<...>: TypeList<char, TypeList<float, TypeListEnd> > {
int item;
};
...
struct Field<...>: struct Field<...>: struct Field<...>: struct Field<TypeListEnd> {
} {
float item;
} {
char item;
} {
int item;
};
这为您提供公共继承包含所有类型的类型串的一个struct
。当然,对这样的struct
做任何有用的事情都是另一回事,只是作为读者的练习。
让我们清楚,一个结构不能继承自身,因为它会递归_ad infinitum_。但这不是你的代码中发生的事情。 –
@jweyrich这不是CRTP;那会是'struct Field:SomeTemplate'。这只是C++ 03类型列表模板元编程。 –
ecatmur
@ecatmur:true!刚刚删除了我的错误评论。 – jweyrich