Problems with C ++ CRTP, error MSVC C2039

MSVC 2008 will not 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 am getting is β€œerror C2039:β€œ type ”: is not a member ofβ€œ D. ”Any ideas?

+4
source share
2 answers

Since B requires a complete definition of type D in order for it to be defined by itself.

What you might expect might be the following:

 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 creating D () (and therefore B ()), the compiler has a full type definition.

+7
source

g ++ gives more useful error messages:

g ++ -c -o / tmp / to / tmp / t.cpp
/tmp/t.cpp: When creating "B:
/tmp/t.cpp:8: created here
/tmp/t.cpp:4: error: invalid use of incomplete type 'struct D
/tmp/t.cpp:7: error: forward declaration 'struct D
/tmp/t.cpp:12: error: ':: main should return' int

+5
source

All Articles