How to get template argument size when using CRTP?

VC ++ 10 gives the following example with error C2027: “using undefined type“ X. ”However, g ++ 4.6 compiles it just fine.

template<class T> class C { static const size_t size = sizeof(T); }; class X : public C<X> { }; 

So which one is right? And how do I do this to make it work on mainstream compilers?

This is not a huge deal because VC ++ still allows sizeof (T) inside C member functions. I just need to repeat some long type definitions that are annoying.

EDIT: I understand that my example was bad, because I really wanted to use size as a compile-time constant, this way:

 template<size_t size> class C2 { }; template<class T> class C { typedef C2<sizeof(T)> A; }; class X : public C<X> { }; 

Both compilers reject this, so I assume this is probably not possible, but as I said, I can still use size functions inside. I just hoped that I would not have to repeat typedef inside every function.

 template<size_t size> class C2 { }; template<class T> class C { void foo() { typedef C2<sizeof(T)> A; } }; class X : public C<X> { }; 
+7
source share
1 answer

A static member cannot be initialized in the class itself, because the type T is defined and not yet complete.

However, you can initialize it outside the class as follows:

 template<class T> class C { static const size_t size; }; template<typename T> const size_t C<T>::size = sizeof(T); //initialization of the static member 

He must compile a fine: http://ideone.com/6sNgN

+6
source

All Articles