考虑以下头文件:
template <typename T> struct tNode
{
T Data; //the data contained within this node
list<tNode<T>*> SubNodes; //a list of tNodes pointers under this tNode
tNode(const T& theData)
//PRE: theData is initialized
//POST: this->data == theData and this->SubNodes have an initial capacity
// equal to INIT_CAPACITY, it is set to the head of SubNodes
{
this->Data = theData;
SubNodes(INIT_CAPACITY); //INIT_CAPACITY is 10
}
};
现在考虑来自另一个文件的一行代码:
Now consider a line of code from another file:
list<tNode<T>*>::iterator it(); //iterate through the SubNodes
编译器给了我这个错误信息:Tree.h:38:17: error: need 'typename' before 'std::list<tNode<T>*>::iterator' 因为 'std::list
The compiler is giving me this error message: Tree.h:38:17: error: need ‘typename’ before ‘std::list<tNode<T>*>::iterator’ because ‘std::list<tNode<T>*>’ is a dependent scope
我不知道为什么编译器会为此对我大喊大叫.
I have no idea why the compiler is yelling at me for this.
在list中,你有一个依赖名称,即依赖于模板参数的名称.
In list<tNode<T>*>::iterator, you have a dependant name, that is, a name that depends on a template parameter.
因此,编译器无法检查 list(此时它没有定义),因此它不知道 >list 要么是静态字段,要么是类型.
As such, the compiler can't inspect list<tNode<T>*> (it doesn't have its definition at this point) and so it doesn't know whether list<tNode<T>*>::iterator is either a static field or a type.
在这种情况下,编译器假定它是一个字段,因此在您的情况下它会产生语法错误.要解决这个问题,只需在声明前放置一个 typename 来告诉编译器它是一个类型:
In such a situation, the compiler assumes that it is a field, so in your case it yields a syntax error. To solve the issue, just tell the compiler that it is a type by putting a typename ahead of the declaration:
typename list<tNode<T>*>::iterator it
这篇关于C++ 模板类型名迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
为什么两个函数的地址相同?Why do two functions have the same address?(为什么两个函数的地址相同?)
为什么 std::function 的初始化程序必须是可复制构Why the initializer of std::function has to be CopyConstructible?(为什么 std::function 的初始化程序必须是可复制构造的?)
混合模板与多态性mixing templates with polymorphism(混合模板与多态性)
我什么时候应该使用关键字“typename"?使用模When should I use the keyword quot;typenamequot; when using templates(我什么时候应该使用关键字“typename?使用模板时)
依赖名称解析命名空间 std/标准库Dependent name resolution amp; namespace std / Standard Library(依赖名称解析命名空间 std/标准库)
gcc 可以编译可变参数模板,而 clang 不能gcc can compile a variadic template while clang cannot(gcc 可以编译可变参数模板,而 clang 不能)