- // Template2.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <iostream>
- #include <string>
- #include <list>
- using namespace std;
- template<class T>
- void PrintColl(T const& coll)
- {
- typename T::const_iterator pos;
- typename T::const_iterator end(coll.end());
- for (pos = coll.begin(); pos != end; pos++)
- {
- cout << *pos << ' ';
- }
- cout << endl;
- }
- int main()
- {
- list<string> lsStr;
- lsStr.push_back("hello");
- lsStr.push_back("andylin");
- lsStr.push_back("congfeng");
- lsStr.push_back("lfp");
- PrintColl(lsStr);
- return 0;
- }
在这个 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;