C ++模板typename迭代器 [英] C++ template typename iterator

查看:439
本文介绍了C ++模板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
    }

};

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

Now consider a line of code from another file:

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

编译器给我这个错误信息: Tree.h:38:17:错误:在'std :: list< tNode< T> *> :: iterator'之前需要'typename'因为'std :: list< tNode< T> *>'是一个依赖项范围

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.

推荐答案

列表< tNode< T> *> :: iterator 中,您有一个依赖名称,即依赖于模板参数的名称。

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

因此,编译器无法检查 list< tNode< T> *> (它没有'此时有定义)因此它不知道 list< tNode< T> *> :: 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 ++模板typename迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆