您的位置:首页 > 编程语言 > C语言/C++

C++自定义模板类中STL iterator未定义的问题

2016-06-30 19:51 204 查看

C++自定义模板类中STL iterator未定义的问题

最近在写一个模板类用到了stl map迭代器,遇见一下问题

#include <map>
#include <iostream>
using namespace std;
template <class T>
class A
{
public:
void iterate() {
map<int, T>::iterator itr;
for(itr = map_.begin(); itr != map_.end(); ++itr) {
cout<<itr->first<<endl;
}
}

private:
map<int, T> map_;
};


编译如上代码,得到如下错误:

template_test.h: In member function
‘void A<T>::iterate()’
:

template_test.h:9: error: expected ‘;’ before ‘itr’

template_test.h:10: error: ‘itr’ was not declared in this scope

错误的原因在于编译器不清楚
map<int, T>::iterator
是一个类型,需要加上typename关键字来帮助编译器做判断

map<int, T>::iterator itr
改为
typename map<int, T>::iterator itr


编译器为什么不清楚呢?因为iterator可能是
map<int, T>
的一个成员变量而不是一个类,这样的话使用iterator来声明一个变量就会出现以上错误。

而在一个非自定义模板类中使用
map<int,int>::iterator itr
就不会有问题,是因为编译器能够明确找到该iterator的地址,从而能够判断出其是一个类型而不是成员变量。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言