C++ CRTP问题,MSVC错误C2039

4 c++ crtp

MSVC 2008不会编译此代码:

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

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

void main()
{
   D d;
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是"错误C2039:'type':不是'D'的成员".有任何想法吗?

Dan*_*nyT 7

因为B需要D的完整类型定义才能自己定义.

你可能期待的可以如下:

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

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

void main()
{
   D d;
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为在实例化D()(以及B())时,编译器具有完整的类型定义.


lot*_*har 5

g ++提供了更多有用的错误消息:

g ++ -c -o/tmp/to /tmp/t.cpp
/tmp/t.cpp:在实例化'B'时:
/tmp/t.cpp:8:从这里实例化
/tmp/t.cpp:4:错误:无效使用不完整类型'struct D'/
tmp/t.cpp:7:错误:'struct D'/ tmp/t.cpp:12的前向声明
:错误:':: main'必须返回'int'