在模板类中定义迭代器时出现STL编译错误

Jea*_*ean 5 c++ stl

下面的代码给出了错误:

error: type ‘std::list<T,std::allocator<_Tp1> >’ is not derived from type ‘Foo<T>’
error: expected ‘;’ before ‘iter’

#include <list>

template <class T> class Foo 
{
  public:
      std::list<T>::iterator iter;

  private:
      std::list<T> elements;
};
Run Code Online (Sandbox Code Playgroud)

为什么以及这应该是正确的?

Tro*_*nic 7

你需要typename std::list<T>::iterator.这是因为list依赖于模板参数,因此编译器无法知道iterator它内部的名称究竟是什么(从技术上讲,它可以知道,但C++标准不能这样工作).该关键字typename告诉编译器以下内容是类型的名称.