在模板类中定义迭代器时出现 STL 编译错误
下面的代码给出了错误:
错误:类型“std::list
” >'不是从类型“Foo ”派生
错误:预期为“;”在“iter”之前
#include <list>
template <class T> class Foo
{
public:
std::list<T>::iterator iter;
private:
std::list<T> elements;
};
为什么这应该是正确的?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要
typename std::list::iterator
。这是因为list
依赖于模板参数,因此编译器无法知道其中的名称iterator
到底是什么(好吧,从技术上讲它可以知道,但是C++ 标准不是这样工作的)。关键字typename
告诉编译器接下来是类型的名称。You need
typename std::list<T>::iterator
. This is becauselist
depends on the template parameter, so the compiler cannot know what exactly is the nameiterator
within it going to be (well, technically it could know, but the C++ standard doesn't work that way). The keywordtypename
tells the compiler that what follows is a name of a type.你需要一个类型名称
You need a typename