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

来源:互联网 发布:js单选按钮取消选中 编辑:程序博客网 时间:2024/05/22 00:38

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的地址,从而能够判断出其是一个类型而不是成员变量。

0 0
原创粉丝点击