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