This final example in typelists section demonstrates a way to generate hierarcy of classes based on such typelist. For example, assume that we have a list of (int, double, std::string), and we would like to define following interface:
struct AbstractVisitor {
   void operator()(const int&) = 0;
   void operator()(const double&) = 0;
   void operator()(const std::string&) = 0;
}; 

In other words, we would like to add operator() for each of the types in the list. But we can write the same interface in a slight different way:
struct AbstractVisitor_1 {
   void operator()(const int&) = 0;
};
struct AbstractVisitor_2 : public AbstractVisitor_1 {
   void operator()(const double&) = 0;
};
struct AbstractVisitor : public AbstractVisitor_2 {
   void operator()(const std::string&) = 0;
}; 


And such hierarchy can be generated using a simple metaprogram:
template <typename LIST> struct AbstractVisitor;

template <typename HEAD, typename TAIL>
struct AbstractVisitor< typelist<HEAD, TAIL> > 
   : public AbstractVisitor<TAIL>
{
   virtual void operator()(const HEAD&) = 0;
};

template <>
struct AbstractVisitor<nulltype> {};

In this example the "recursion" is in the inheritance: we define that AbstractVisitor< typelist<HEAD, TAIL> > extends AbstractVisitor<TAIL>.

Last edited Nov 30, 2007 at 8:04 PM by migo, version 1

Comments

No comments yet.