JTeagle
JTeagle

Reputation: 2196

sizeof() And Template Argument In ctor / Non-ctor Function

I hit a snag today... I wanted to define a small templated helper class:

template<class T>
CMyClass
{
public : 
    CMyClass() { size_t iSize = sizeof(T); } // Allowed. 
    size_t GetElementSize() const { return sizeof(T); } // C2027.
}; 

and of course, it wouldn't compile (C2027). My question was, is it possible to get the size of the type? The reason I need this is that the type the object is constructed with could be a number of differently-defined structures, and so I need to get the size of the structure used, at run time.

Through a quick bit of experimentation, because I'm stubborn, it seems that I can use sizeof(T) in the ctor, but not in the non-ctor function - so my question now is... why?!

Upvotes: 0

Views: 2264

Answers (3)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507005

It can have different reasons. Consider this code:

// file foo.h
class X;

template<class T>
class CMyClass
{
public : 
    CMyClass() { size_t iSize = sizeof(T); } // Allowed. 
    size_t GetElementSize() const { return sizeof(T); } // C2027.
};

struct Class {
  Class(); // definition of it in the cpp file, where "X" is fully defined
  void callit() { cm.GetElementSize(); } // instantiated here!
  CMyClass<X> cm;
};

At the time the constructor is instantiated (in the ".cpp" file), T is a completely defined type. But at the time GetElementSize is instantiated (in the ".h" file), X is not yet completely defined.

Upvotes: 2

Kim Gr&#228;sman
Kim Gr&#228;sman

Reputation: 7586

Seems to work fine here, what's the message of C2027? And what compiler are you using?

Upvotes: 2

i_am_jorf
i_am_jorf

Reputation: 54600

Not sure what the proper answer to your question is, but it seems you can work around it by just making iSize a member and have GetElementSize() return it instead of calling sizeof again.

Upvotes: 1

Related Questions