typename 的高级用法1

  1. // Template2.cpp : Defines the entry point for the console application.
  2. //
  3. #include "stdafx.h"
  4. #include <iostream>
  5. #include <string>
  6. #include <list>
  7. using namespace std;
  8. template<class T>
  9. void PrintColl(T const& coll)
  10. {
  11.     typename T::const_iterator pos;
  12.     typename T::const_iterator end(coll.end());
  13.     for (pos = coll.begin(); pos != end; pos++)
  14.     {
  15.         cout << *pos << ' ';
  16.     }
  17.     cout << endl;
  18. }
  19. int main()
  20. {
  21.     list<string> lsStr;
  22.     lsStr.push_back("hello");
  23.     lsStr.push_back("andylin");
  24.     lsStr.push_back("congfeng");
  25.     lsStr.push_back("lfp");
  26.     PrintColl(lsStr);
  27.     return 0;
  28. }

在这个 function template 中,coll 是个 STL 容器,其元素类型为 T。这里使用了 STL 容器的迭代器类型(iterator type)遍历 coll 的所有元素。迭代器类型为const_iterator,每一个STL 容器都声明有这个类型:
class stlcontainer {
...
typedef ... iterator; // 可读可写的迭代器
typedef ... const_iterator; // 惟读迭代器
...
};
使用 template type T 的 const_iterator 时,你必须写出全名,并在最前面加上关键词 typename:
typename T::const_iterator pos;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值