您的位置:首页 > 其它

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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: