Is recursive explicit template template creation possible?

Given a pattern like

template<int dim> class Point { ... }; 

this template can be created explicitly as

 template class Point<0>; template class Point<1>; template class Point<2>; template class Point<3>; 

instead of instantiating each template individually as above, I would like to create recursive instances with a single call of type

 template class RecursiveInstantiate<Point, 3>; 

where RecursiveInstantiate<T, i> will instantiate T<i> , T<i-1> , ..., T<0> . How can I create such a RecursiveInstantiate class? If this is not possible, do you know how to do this with a preprocessor?

Actually, I'm interested in generalizing this for classes with several template parameters, such as Node<int i1,int i2,int i3> for all combinations i1, i2, i3 in {0,1,2,3}. But I hope that I can independently work out this second part.

Any advice is welcome, along with an explanation of why this is not possible, what I want to achieve.


Update: Thank you for your comments. Now I see more clearly where the problem really is. Line

 template class Point<3>; 

creates an instance of the template and exports its characters to the object file. Form implementation

 template class RecursiveInstantiate<Point, 3>; 

can create instances of classes class Point<3> , class Point<2> , .... Apparently, this happens only locally. Templates are not exported to the object file. I may have to look for a solution using a preprocessor.

As I see now, I did not ask my question accurately enough at the beginning, I appreciate your answers and those chosen as correct.

Note: I am trying to use this on linux with g ++ / clang as compilers.

+5
c ++ templates
source share
2 answers

You can create a small Instantiator class:

 template <unsigned int N> struct Instantiator { Point<N> p; Instantiator<N-1> i; }; template <> struct Instantiator<0> { Point<0> p; }; 

Then just add one explicit instantiation: template struct Instantiator<81>;

You can extend this idea lexicographically to any number of integral parameters.


As @Georg says, let it become shared:

 template <template <unsigned int> class T, unsigned int N> struct Instantiator { T<N> t; Instantiator<T, N-1> i; }; template <template <unsigned int> class T> struct Instantiator<T, 0> { T<0> t; }; template struct Instantiator<Point, 82>; 
+8
source share

You can do it like this:

 template<int dim> struct Point { static const int val = dim; Point<dim - 1> p; }; template<> struct Point<0> { ... }; 

This creates a template specialization for the template parameter when it is 0 , so recursion stops there when you create an instance of this type:

 Point<4> 

It instantiates Point<4> to Point<0> . Then you can do

 Point<4>::val 

to access the value of this particular.

+4
source share

All Articles