tags:

views:

340

answers:

2

MSVC 2008 won't compile this code:

template <class Derived>
struct B
{
   typename Derived::type t;
};

struct D : B<D>
{
   typedef int type;
};

void main()
{
   D d;
}

The error I get is "error C2039: 'type' : is not a member of 'D'". Any ideas?

+4  A: 

g++ gives more helpful error messages:

g++ -c -o /tmp/t.o /tmp/t.cpp
/tmp/t.cpp: In instantiation of ‘B’:
/tmp/t.cpp:8: instantiated from here
/tmp/t.cpp:4: error: invalid use of incomplete type ‘struct D’
/tmp/t.cpp:7: error: forward declaration of ‘struct D’
/tmp/t.cpp:12: error: ‘::main’ must return ‘int’

lothar
Thanks for that, Lothar. Looks like it's a C++ thing, and not a non-compliant compiler thing then.
+7  A: 

Because B requires the complete type definition of D in order to be itself defined.

What you're perhaps expecting can be had as follows:

template <class Derived>
struct B
{
   B() {
     typename Derived::type t;
   }
};

struct D : B<D>
{
   typedef int type;
};

void main()
{
   D d;
}

This works because, at the time of instantiation of D() (and hence B()), the compiler has a complete definition of the type.

DannyT
Oh, brilliant, of course. Thanks DannyT!