Templating off of an arbitirary-length list of types in C++

507 Views Asked by At

Here's what I want to be able to type:

class foo : public watchKeys<A, B, C> {}; //Or any list of keys

Boost::mpl has sequences, which allow you to do this, but I don't want to have to do:

class foo : public watchKeys<mpl::list<A, B, C> > {};

I don't mind it being "ugly" or verbose on the inside, but I want the way watchKeys is ultimately used to be very simple and intuitive. I also can't figure out how boost is doing it, but that seems to be because there's a layer of macros between me and templates.

How might I go about this? I'd prefer not to do the giant list of templates for each number of types, but if that's the only it's the only way...

Edit: I've become fairly certain that there's no way to do what I want to do (almost, but you can't have a variable number of macro arguments), but the question is still generating useful and informative answers.

2

There are 2 best solutions below

4
On BEST ANSWER

The giant list of templates for each number of types is the only way to do it in the current version of C++. See boost::tuple for an example of how to go about.

C++0X supports variadic templates, but that isn't well supported yet (I think modern version of GCC have experimental support though).

3
On

Alternatively you can do it recursively

template<typename Head, typename Tail>
struct list { };

struct emptylist { };

class foo : public watchKeys<list<A, 
                             list<B, 
                             list<C, emptylist> > > > { };

You can then process it like this

template<typename List>
struct process;

template<typename Head, typename Tail>
struct process< list<Head, Tail> > : process<Tail> { 
  // process Head
};

template<>
struct process<emptylist> { };