Usage of typelist
Is Typelist(开发者_JS百科in the sense of Alexandrescu define it) mainly/essentialy useful for generate hierarchy of class (and maybe for class like boost::tuple ) or is there plenty of other domains where typelist is very useful ?
Its also used in Mixin-Based Programming in C++ described by Ulrich W. Eisenecker, Frank Blinn, and Krzysztof Czarneck.
I believe you're referring to something like a linked list of templates.
This is a fundamental structure in template metaprogramming. Template metaprogramming has various applications, where the programmer encodes a problem in templates and the metaprogram implements an algorithm to solve it.
Boost Spirit is often cited as a prime example of template metaprogramming, although unfortunately I can't tell you much about it.
It seems to me that typelists are most useful as a building block for other generic libraries rather than being used directly in client code. Don't use a lower-level tool if Boost tuples or MPL are flexible enough to do what you need. But there's nothing to say you couldn't use typelists directly if you need that kind of flexibility.
We use a typelist as a sort of type-safe composition, but where each child is accessible through a single interface:
// Defining a typelist:
typedef TypeList<A,
TypeList<B,
TypeList<C, NullType> > > MyTypeList;
MyTypeList tl;
// Setting values in the typelist:
A a;
tl.set(a);
C c;
tl.set(c);
tl.tail().head() = newB;
// Retrieving values from the typelist:
C c = tl.get<C>();
B b = tl.tail().head();
// To reinitialize a value:
tl.reset<B>();
tl.set(B());
// To get total size:
int size = tl.count();
Beyond that, there's an interface for iterating and built-in support for functors.
The benefit is that you can either treat the children independently or homogeneously, depending on the need.
The downside is that you sacrifice a certain amount of abstractness. Things become much more concrete. It also introduces a new way of dealing with composition, which is something new to learn for others who need to work with the code.
For us, in the place we used it, it was a good fit.
精彩评论