我想在一些模板函数中迭代一个容器。如果容器是双端队列但它存储的类型是未知的,我试过:
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;
}
两者都给出编译错误。如何在模板函数内创建一个迭代器,以便我可以迭代容器?
最佳答案
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 是确实需要这一说明的编译器之一。
关于c++ - 接收容器作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20054631/