C++ 模板编译错误 - 递归类型或函数依赖

标签 c++ templates

我写了一个编译错误的模板类

template<class T>
class Entity
{
    string EntityName;
    int  EntitySize;
    Entity<T*> pPrev;
    Entity<T*> pNext;
public:
    Entity<T>(const string & name, int size)
    {
        EntityName = name;
        EntitySize = size;
    }
    //member functions
};

我正在使用 MSVC++ 2008,错误是:

fatal error C1202: recursive type or function dependency context too complex

我没有在我的课上写过任何递归函数。那为什么会出现这个错误呢?请帮忙。

最佳答案

好的。我正在向您解释您面临的问题。但首先是第一件事。你说:

I wrote a template class which is giving compilation error

首先,就C++而言,没有“模板类”这样的东西,只有“类模板”。这句话的读法是“类的模板”,而不是“函数模板”,后者是“函数的模板”。再次声明:类不定义模板,模板定义类(和函数)。* 引自 here .

现在,让我们看看错误:

fatal error C1202: recursive type or function dependency context too complex

错误说明了一切。 $14.7.1来自标准的解释很好地解释了问题的原因,甚至给你一个非常接近你正在做的事情的例子。所以我什至不需要自己写一个字。这是 $14.7.1

4 There is an implementation-defined quantity that specifies the limit on the total depth of recursive instantiations, which could involve more than one template. The result of an infinite recursion in instantiation is undefined. [ Example:

template < class T > class X {
X<T >* p; // OK
X<T*> a; //implicit generation of X<T> requires
         //the implicit instantiation of X<T*> which requires
         //the implicit instantiation of X<T**> which ...
};

—end example ]

请用X<T*> a阅读评论,你也差不多是这种情况。所以你的问题不是因为递归函数,而是因为类模板的递归实例化,由这些行引起:

  Entity<T*> pPrev;
  Entity<T*> pNext;

希望,它能解决您的问题!


编辑:但我想知道你想用 Entity<T*> pPrev 达到什么目的? ?这似乎是一个错字,你可能想写 Entity<T>* pPrev .与 pNext 相同.是这样吗?

还有一条改进设计的建议:使用成员初始化列表,而不是赋值。也就是说,按照以下方式编写您的构造函数,

    Entity<T>(const string & name, int size) : EntityName(name), EntitySize(size)
    {
       //all assignments moved to initialization list.
    }

读这个:Why should I prefer to use member initialization list?

关于C++ 模板编译错误 - 递归类型或函数依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4357854/

相关文章:

c++ - c中的类型提升和转换

c++ - 为什么 head 值不是 "NULL"?

C++ sax2解析器问题

json - 在同一Logstash配置文件中使用多个Elsticsearch输出时,将忽略模板

c++ - 为什么在派生类c++中找不到基类成员

c++ - 模板中的数据类型错误

c++ - 使用 reinterpret_cast 将函数强制转换为 void*,为什么不违法?

c++ - 模板非类型模板参数?

c++ - C++通过迭代器确定变量类型

c++ - 简单 CRTP 案例中没有名为 "XXX"的成员