7

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> { };
Timo
  • 5,125
  • 3
  • 23
  • 29

1 Answers1

6

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

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • I don't think this is the issue here because integral compile-time constants can normally be initialized inside the class. I might accept it as a workaround though. – Timo Dec 17 '11 at 12:35
  • @Timo: That is exactly the issue. By the time, the static member is parsed *and an attempt is being made to initialize it*, the type `T` is not yet complete. – Nawaz Dec 17 '11 at 12:38