Let's say I have a class template like this (you can't change grid, it represents a more difficult object, I don't like to change):
template<int x, int y>
class grid{
public:
double S[x][y];
grid();
~grid();};
Now I wish a new class template (named multi_grid), which owns an array my_grids. I like to store into my_grids different grids like (pseudo code):
my_grids[0]=grid<x*1,y*1>,
my_grids[1]=grid<x*2,y*2>
my_grids[n]=grid<(x<<n),(y<<n)>
My idea is to use void* for my_grids and set it via constructor. My trouble starts in the constructor:
template<int x, int y, int degree>
class multi_grid{
public:
void* my_grids[degree];
~multi_grid(){};
multi_grid(){
create_grid<degree-1>();
}
template<int grid_number>
void create_grid(void){
my_grid[grid_number]=new grid<(x<<grid_number), (y<<grid_number)>;
create_grid<grid_number-1>();
}
};
template<int x, int y, int degree>
template<int grid_number>
void multi_grid<x, y, degree>::create_grid<-1>(){}
I have 2 questions:
- Is the concept of the idea possible?
- and if first answer is true, how to do it? I started with a simple for_loop, which leads to trouble, since i++ is not static. So I tried template recursion, than I run into different problems like: "shadows template parm" or "function template partial specialization ‘create_grid<-1>’ is not allowed" and a lot more trouble.
I tried the whole to solve it and couldn't figure it out. Thanks in advance.
The size is part of your type. By resorting to
void *
you nuke it, to an extent.An alternative is to just use vectors. This will still allow you to have different sized grids in an container and get or set the data.