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

发布于 2024-08-21 00:41:50 字数 403 浏览 3 评论 0 原文

下面的代码给出了错误:

错误:类型“std::list” >'不是从类型“Foo”派生
错误:预期为“;”在“iter”之前

#include <list>

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

  private:
      std::list<T> elements;
};

为什么这应该是正确的?

The code below gives the error:

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

Why and what should this be to be correct?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伴随着你 2024-08-28 00:41:50

您需要typename std::list::iterator。这是因为 list 依赖于模板参数,因此编译器无法知道其中的名称 iterator 到底是什么(好吧,从技术上讲它可以知道,但是C++ 标准不是这样工作的)。关键字typename告诉编译器接下来是类型的名称。

You need typename std::list<T>::iterator. This is because list depends on the template parameter, so the compiler cannot know what exactly is the name iterator within it going to be (well, technically it could know, but the C++ standard doesn't work that way). The keyword typename tells the compiler that what follows is a name of a type.

纵山崖 2024-08-28 00:41:50

你需要一个类型名称

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

    private:
        std::list<T> elements;
};

You need a typename

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

    private:
        std::list<T> elements;
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文