c++ storing arbitrary number of different classes in one class-member-array

77 views Asked by At

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:

  1. Is the concept of the idea possible?
  2. 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.

1

There are 1 answers

2
doctorlove On

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.

#include <vector>

class grid
{
public:
    grid(int x, int y)
    {
        data.resize(x);
        //and each y
    }
//private: //maybe - up to you
    std::vector<std::vector<double>>data;
};

int main()
{
    std::vector<grid> my_grids;
    my_grids.emplace_back(1, 3);
}