模板类内部的模板类-不同的参数

时间:2020-08-27 04:19:06

标签: c++ c++11 templates iterator

是否可以在如下所示的模板类中创建模板类

// Container.h
template <typename T>
class Container
{
private:
  using iterator = Iterator<Node<T>>;
  using const_iterator = Iterator<const Node<T>>;

  // Node struct to hold data.
  template <typename T>
  struct Node
  {
    T data_;
  };

public:
  // Templated iterator for const or non-const.
  template <typename NodeType>
  class Iterator
  {
  private:
    NodeType* node_;
  
  public:
    Iterator();
  };
};

#include "Container.tpp"

因此,我在这里声明一个迭代器的模板,该模板采用一个NodeType,它不同于容器类模板采用的T

如果可能的话,如何在另一个文件中实现Iterator()?像

// Container.tpp
template <typename T>
LinkedList<T>::LinkedListIterator<NodeType>::Iterator()
{
  // Implementation ...
}

这似乎不正确,因为我无权访问NodeType。任何建议将不胜感激。

1 个答案:

答案 0 :(得分:2)

您应该将其定义为

template <typename T>        // for the enclosing class template
template <typename NodeType> // for the member template
Container<T>::Iterator<NodeType>::Iterator()
{
  // Implementation ...
}

顺便说一句:成员类模板Node不能使用与外部类模板相同的模板参数名称T