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

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值