开发者

Using templates to make items of varying length stay on stack?

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?


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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜