简体   繁体   中英

How to get the size of a template argument when using CRTP?

In VC++10 the following example fails with error C2027: "use of 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 would I do this so that it works on mainstream compilers?

It's not a huge deal though, cause VC++ still allows sizeof(T) inside member functions of C. I just have to repeat some long type definitions which is annoying.

EDIT: I realize my example was bad because what I really wanted to do was to use the size as a compile time constant, in 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 it's probably not possible, but like I said I can still use sizeof inside functions. I was just hoping I wouldn't have to repeat the 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> { };

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

However, you can initialize it outside the class as:

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

It should compile fine: http://ideone.com/6sNgN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM