Reputation: 2196
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
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
Reputation: 7586
Seems to work fine here, what's the message of C2027? And what compiler are you using?
Upvotes: 2
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