接收容器作为模板参数

时间:2013-11-18 18:04:49

标签: c++ templates g++-4.7

我想在一些模板函数中迭代一个容器。如果容器是deque但是它存储的类型不知道那么,我试过:

template <typename T>
void PrintDeque(deque<T> d)
{
    deque<T>::iterator it; //error here
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

如果我为未知容器尝试此操作:

template <typename T>
void PrintDeque(T d)
{
    T::iterator it;   //error here
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

两者都会出现编译错误。如何在模板函数中创建一个迭代器,以便我可以迭代容器?

3 个答案:

答案 0 :(得分:2)

template <typename T>
void PrintDeque(T d)
{
    typename T::iterator it;   //error here
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

您之前需要typename,因为编译器不知道您正在命名类型或静态变量。它被称为依赖类型。

http://pages.cs.wisc.edu/~driscoll/typename.html

作为旁边并评论其他答案。有些编译器不需要这个,有些则需要。海湾合作委员会是需要澄清的编制者之一。

答案 1 :(得分:0)

您可以使用此代码:

template <typename T>
void PrintDeque(deque<T> d)
{
    deque<T>::iterator it;
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

此代码在我的windows上使用vs12时效果很好。


注意:

template <typename T>
void PrintDeque(deque<T> d)
{
    deque<typename T>::iterator it; //error here
    for(it=d.begin();it!=d.end();it++)
        cout<<*it<<" ";
    cout<<endl;
}

此代码,您发布的内容在我的计算机上运行正常。

答案 2 :(得分:0)

#include <deque>
#include <iostream>
using namespace std;

template<typename range>
void PrintEverythingIn(range C)
{
        for (auto e : C)
                cout << e << ' ';
        cout << endl;
}

deque<int> demo { 1,2,3,4,5,6,7,8,9,10,1,2,3,4,5,6,7,8,9,20 };

int main() { PrintEverythingIn(demo); }
相关问题