C++ 模板类型名迭代器

标签 c++ templates iterator typename

考虑以下头文件:

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
    }

};

现在考虑另一个文件中的一行代码:

list<tNode<T>*>::iterator it();  //iterate through the SubNodes

编译器给了我这个错误信息:Tree.h:38:17: error: need ‘typename’ before ‘std::list<tNode<T>*>::iterator’ because ‘std::list<tNode<T>*>’ is a dependent scope

我不知道为什么编译器会为此对我大喊大叫。

最佳答案

list<tNode<T>*>::iterator ,你有一个依赖名,也就是一个依赖于模板参数的名字。

因此,编译器无法检查 list<tNode<T>*> (此时它没有定义)因此它不知道 list<tNode<T>*>::iterator是静态字段或类型。

在这种情况下,编译器假定它是一个字段,因此在您的情况下它会产生语法错误。要解决这个问题,只需通过输入 typename 告诉编译器它是一个类型。在声明之前:

typename list<tNode<T>*>::iterator it

关于C++ 模板类型名迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11275444/

相关文章:

c++ - 理解 C++ 中的迭代器类

c++ - 如何将 DRY 原则应用于 C++ 中的迭代器? (迭代器、const_iterator、reverse_iterator、const_reverse_iterator)

.net - 将透明 png 图像转换为位图时,它不保留透明度?

c++ - 自定义迭代器类中的重载 `!=` 运算符无法正常工作

c++ - 编译时 C++ 项目抛出错误 C2228,这不是预期的,因为控件在运行时未到达该点

c++ - 将编译时已知函数参数转换为 std::integral_constant 的有效方法

ruby - 枚举器的未定义方法排序

c++ - C++中跨线程的变量可见性

c++ - 最佳实践 : using namespace or reopen namespace?

c++ - '{' token 错误之前的预期类名