tags:

views:

95

answers:

2

The situation is that I have an array of items, and the items have an array inside. However, I want to make the array inside of variable length at declaration time, yet resizable at compile time.

So I would want something like:

class2<16>[] = new class2<16>[2048*1024];

Or whatever. Hopefully you get the idea.

Obviously making it have fixed array inside is easy, but the problem is the array can be HUGE so I don't want to have 2048*1024 calls to new, so I definitely don't want class2 to call any new or delete methods.

Is this even possible?

+5  A: 

You can create a template parameter for your internal array-size. For example:-

template<int siz>
class Item{
  int arr[siz];
};

int main() {
  Item<15> items[10];
  return 0;
}
Abhay
Thanks, I think that will work.
Charles Eli Cheese
+3  A: 

std::tr1::array (addition to standard library in C++0x) and boost::array already exist, taking two template parameters: the type and count of items:

std::tr1::array<int, 16> something;

You can have any number of those arrays at run-time with the std::vector container:

std::vector<std::tr1::array<int, 16> > lots_of_arrays(2048*1024);

Only one dynamic allocation involved here.

visitor