I remember seing something like this being done:
template <ListOfTypenames>
class X : public ListOfTypenames {};
that is, X inherits from a variable length list of typenames passed as the template arguments. This code is hypothetical, of course.
I can't find any reference for this, though. Is it possible? Is it C++0x?
As others already answered, variadic templates are part of the next standard, but can be emulated in current C++. One convenient tool for this is to use the Boost.MPL library. In your code, you write a single template parameter (let's name it "Typelist"), and the users of your template wrap the typelist in an MPL sequence. Example:
In the implementation of "YourType", you can access the elements in Typelist with various metafunctions. For example,
at_c<Typelist, N>
is theN
th element of the list. As another example, the "X" class in your question could be written withinherit_linearly
as:Variable number of templates is part of the next C++ standard. However, you can get a taste of it if you're using GCC (from version 4.3). Here's a list of available C++0x features in GCC. You're looking for Variadic Templates.
By the way, if you need a formal reference on how to achieve the inheritance mechanism as described by Earwicker, it's on the book C++ Templates.
Sounds like you are referring to C++0x Variadic Templates. You can also achieve the same effect using Alexandrescu's TypeList construct from Loki.
I believe the variadic template syntax in question would look like the following.
You can do it in current C++. You give the template a "large enough" number of parameters, and you give them defaults:
Or you can get more sophisticated and use recursion. First you forward-declare the template:
Then you specialise for the case where all the parameters are default:
Then you properly define the general template (which previously you've only forward-declared):
Notice how in the base class, you inherit X but you miss the first parameter. So they all slide along one place. Eventually they will all be defaults, and the specialization will kick in, which doesn't inherit anything, thus terminating the recursion.
Update: just had a strange feeling I'd posted something like this before, and guess what...