tags:

views:

58

answers:

4

I'm trying to get the maximum size of any possible instance of my template as a compile time constant. The first thing that came to mind was something like this...

union TestUnion
{
 template<typename T> class MyClass
 {
 public:
  MyClass() { };
  MyClass(T& t) : _t(t) { }

 private:
  T _t;
 };
};

But sizeof(TestUnion) is always equal to 1, but sizeof(MyClass<int>) for instance, correctly returns 4. Anyone have any better ideas?

A: 

You are getting the size of a union that has no members. Declaring a template within a union scope doesn't declare any union members. In C++ (and also I believe C) it is guaranteed that all class or union types occupy at least 1 byte of space. So that's why the size is 1.

There is no way to get the maximum possible size, and that's because a template class can contain an instance of an arbitrary type that's not known until the template is instantiated. This type could be of arbitrary size. I will illustrate what I mean in an edit to this post within an hour or two.

Omnifarious
Right. I understand the issue here. So if I instantiate the template inside of a union, that works. Unfortunately, I'm not sure if that will work for me.
23L
@23L - Well, someone else posted an excellent example, so I won't bother with mine. :-)
Omnifarious
A: 

I'm not an expert when it comes to sizing C++ classes... I'm sure there is a better way. Assuming you want just a potential maximum size for all the instances you plan on using, here is a likely hacky way:

const foo = (sizeof(MyClass) > sizeof(MyClass) ? (sizeof(MyClass) : sizeof(MyClass)

Then repeat to no-end nesting them as needed.

Wes Hardaker
A: 

May be it helps you: link

mr. Vachovsky
+1  A: 
Eric Towers