C++ template typename iterator(C++ 模板类型名迭代器)
问题描述
考虑以下头文件:
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++ 模板类型名迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 模板类型名迭代器
基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
