Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a C++11 variadic class template whose variadic parameter cardinality depends on an integer template parameter?

Sorry for the convoluted question, but basically the idea is very simple. I have a variadic class template:

template<class P1, class P2, class ... P3s>
class A 
{
    ...
};

I would like to have an A-classes generator which takes an integer template parameter N and instantiates an A class with N P3s parameters. Like:

template<class P1, class P2, class P3, int N>
class GenA : /* somehow */ : public A<P1, P2, /* N times */ P3, P3, ...>
{
    ...
};

So usage would be:

// Generates A<Class1, Class2, Class3, Class3, Class3>
GenA<Class1, Class2, Class3, 3> a; 

I have already tried doing that with compile time recursion and partial specialization

template <class P1, class P2, int N, class P3>
class GenA : public GenA<P1, P2, N-1, P3, P3>
{
    ...
}

template <class P1, class P2, int N, class ... P3s>
class GenA<P1, P2, 0, P3s ...> : public A<P1, P2, P3s, ...>
{
    ...
}

however C++11 doesn't recognize the second template to be a specialization of the first one (because it is, in fact, different) and never gets to the base case of the recursion (it stops complaining about too many recursion levels). Any ideas?

Thanks
Tunnuz

like image 519
tunnuz Avatar asked Oct 10 '12 09:10

tunnuz


1 Answers

template<class P1, class P2, class... P3s>
class A {};

template<class... Ps>
struct TypeList {};

template<class P1, class P2, class P3, unsigned N, class P> struct GenHelp;

template<class P1, class P2, class P3, class... Ps>
struct GenHelp<P1, P2, P3, 0, TypeList<Ps...> >
{
   typedef A<P1, P2, Ps... > AType;
};

template<class P1, class P2, class P3, unsigned N, class... Ps>
struct GenHelp<P1, P2, P3, N, TypeList<Ps...> > : public GenHelp<P1, P2, P3, N-1, TypeList<P3, Ps...> >
{};

template<class P1, class P2, class P3, unsigned N>
class GenA : public GenHelp<P1, P2, P3, N, TypeList<> >::AType
{};
like image 162
Seg Fault Avatar answered Sep 23 '22 21:09

Seg Fault