C++ C++;CRTP问题,MSVC错误C2039

C++ C++;CRTP问题,MSVC错误C2039,c++,crtp,C++,Crtp,MSVC 2008不会编译以下代码: template <class Derived> struct B { typename Derived::type t; }; struct D : B<D> { typedef int type; }; void main() { D d; } 模板 结构B { typename派生::类型t; }; 结构D:B { typedef int类型; }; void main() { D; } 我得到的错误是

MSVC 2008不会编译以下代码:

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

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

void main()
{
   D d;
}
模板
结构B
{
typename派生::类型t;
};
结构D:B
{
typedef int类型;
};
void main()
{
D;
}

我得到的错误是“error C2039:'type':不是'D'的成员。有什么想法吗?

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

g++-c-o/tmp/t.o/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'


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

您可能期望的结果如下所示:

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

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

void main()
{
   D d;
}
模板
结构B
{
B(){
typename派生::类型t;
}
};
结构D:B
{
typedef int类型;
};
void main()
{
D;
}

这是因为,在实例化D()时(因此B()),编译器对类型有一个完整的定义。

谢谢你,Lothar。看起来它是C++的东西,而不是一个不符合编译器的东西。