【问题标题】:C++ CRTP issues, MSVC error C2039C++ CRTP 问题,MSVC 错误 C2039
【发布时间】:2009-05-21 03:07:38
【问题描述】:

MSVC 2008 不会编译此代码:

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

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

void main()
{
   D d;
}

我得到的错误是“错误 C2039: 'type' : is not a member of 'D'”。有什么想法吗?

【问题讨论】:

    标签: c++ crtp


    【解决方案1】:

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

    您可能期望的结果如下:

    template <class Derived>
    struct B
    {
       B() {
         typename Derived::type t;
       }
    };
    
    struct D : B<D>
    {
       typedef int type;
    };
    
    void main()
    {
       D d;
    }
    

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 谢谢你,洛萨。看起来这是一个 C++ 的东西,而不是一个不兼容的编译器。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      • 2021-05-16
      • 2011-07-26
      相关资源
      最近更新 更多