t :: iterator的错误,其中模板参数t可能为vector 或list
题
我正在尝试编写一个函数来打印公共STL容器(向量,列表等)的表示形式。我给了该函数一个模板参数t,例如,该参数可能代表向量。我遇到了T型的迭代器遇到问题。
vector<int> v(10, 0);
repr< vector<int> >(v);
...
template <typename T>
void repr(const T & v)
{
cout << "[";
if (!v.empty())
{
cout << ' ';
T::iterator i;
for (i = v.begin();
i != v.end()-1;
++i)
{
cout << *i << ", ";
}
cout << *(++i) << ' ';
}
cout << "]\n";
}
...
brett@brett-laptop:~/Desktop/stl$ g++ -Wall main.cpp
main.cpp: In function ‘void repr(const T&)’:
main.cpp:13: error: expected ‘;’ before ‘i’
main.cpp:14: error: ‘i’ was not declared in this scope
main.cpp: In function ‘void repr(const T&) [with T = std::vector<int, std::allocator<int> >]’:
main.cpp:33: instantiated from here
main.cpp:13: error: dependent-name ‘T::iterator’ is parsed as a non-type, but instantiation yields a type
main.cpp:13: note: say ‘typename T::iterator’ if a type is meant
我尝试了编译器建议的“键入t :: iterator”,但只有一个更神秘的错误。
编辑:感谢您的帮助!这是想要使用此功能的任何人的工作版本:
template <typename T>
void repr(const T & v)
{
cout << "[";
if (!v.empty())
{
cout << ' ';
typename T::const_iterator i;
for (i = v.begin();
i != v.end();
++i)
{
if (i != v.begin())
{
cout << ", ";
}
cout << *i;
}
cout << ' ';
}
cout << "]\n";
}
解决方案
你需要 typename
告诉编译器 ::iterator
应该是一种类型。编译器不知道这是一种类型,因为它在实例化模板之前不知道T是什么。例如,它也可以参考一些静态数据成员。那是你的第一个错误。
您的第二个错误是 v
是参考const. 。所以,而不是 ::iterator
你必须使用 ::const_iterator
. 。您不能向不符合迭代器询问常数容器。
其他提示
改变 T::iterator i;
至 typename T::const_iterator i;
因为 ::iterator
是类型 T
和 v
是一个 const &
.
在合格的依赖类型之前,您需要 typename
。没有 typename
, ,有一个C ++解析规则,称合格的依赖名称应解析为 non-types
即使它导致语法错误。
typename
指出以下名称应视为一种类型。否则,将名称解释为指非类型。
不隶属于 StackOverflow