【问题标题】:Receiving container as template argument接收容器作为模板参数
【发布时间】:2013-11-18 18:04:49
【问题描述】:

我想在某个模板函数中迭代一个容器。如果容器是双端队列但不知道它存储的类型,我试过了:

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;
}

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

【问题讨论】:

  • 尝试 deque::iterator it 或者只使用 auto;
  • 1.通过引用或 const 引用传递 deque。 2. 试试typedef typename T::iterator buffer_iterator; buffer_iterator it;
  • 那个&lt;typename T&gt;是我的错误现在更正了。

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


【解决方案1】:
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

顺便评论一下其他答案。有些编译器不需要这个,有些则需要。 GCC 是需要此说明的编译器之一。

【讨论】:

  • 谢谢。这样可行。第一个代码呢,例如:如果我想限制我的函数只接受双端队列作为容器但包含任何其他数据类型?
  • 得到它的工作谢谢。只需将typename 放在deque&lt;t&gt;::iterator it 之前就可以了!它有效。
【解决方案2】:
#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); }

【讨论】:

    【解决方案3】:

    您可以使用此代码:

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

    这段代码在我的带有 vs12 的 windows 上运行良好。


    注意:

    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;
    }
    

    此代码,您发布的内容在我的计算机上也可以正常工作。

    【讨论】:

    • 这适用于 VS 和 Comeau,但不适用于 GCC
    • 另外,您还没有回答问题,您只是将他的代码粘贴回给他并说它有效。
    • 首先我使用了我通常使用的东西,即 deque::iterator it;而不是 deque::iterator it;那行得通。之后尝试发布的代码。这也奏效了。
    • @juanchopanza 我不知道。任何参考都会非常有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多