typename 的高级用法1
2008-12-01 23:20
99 查看
// 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;
//
#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;
相关文章推荐
- typename 的高级用法2
- jquery ajax实例教程和一些高级用法
- Firebug高级用法 - Web开发的利器
- 关于Sysstat的高级用法综合版本(一)
- Hbase 笔记(9) 高级用法
- Selenium WebDriver高级用法
- cocoaPods高级用法
- makefile高级用法--隐含规则
- git高级用法
- sed高级用法:模式空间(pattern space)和保持空间(hold space)
- printf高级用法记录 - 1
- JAVA高级:反编译工具jad的简单用法
- css类选择符高级用法:多类选择符
- Ping高级用法:懒网管们的福音
- 属性动画的高级用法
- Android属性动画高级用法
- 回调函数的高级用法
- C++学习:引用和函数的高级用法
- sscanf和sprintf的高级用法
- React-Router 高级用法