C++ 模板类型名迭代器

C++ template typename iterator(C++ 模板类型名迭代器)
本文介绍了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*>::iterator中,你有一个依赖名称,即依赖于模板参数的名称.

In list<tNode<T>*>::iterator, you have a dependant name, that is, a name that depends on a template parameter.

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

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++ 模板类型名迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)