0

Is it possible to create a template class inside a template class like the following

// 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"

So here I declare a template for an iterator that takes in a NodeType which is different from the T that the container class template takes.

If this is possible to do, how do I implemenet the Iterator() inside a different file? Something like

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

This does not seem right since I do not have access to the NodeType. Any advice would be appreciated.

3
  • A "template class inside a template class" would mean, for example, that a container of int needs nodes of int as well as nodes of char, nodes of float, nodes of std::vector< std::map<int, std::string> >, etc. That is probably not what you meant. Perhaps you want to rewrite your question to explain what you want instead of trying to explain via code?
    – JaMiT
    Aug 27, 2020 at 4:30
  • @JaMiT I think songuanyao already answered it.
    – nick2225
    Aug 27, 2020 at 4:32
  • I think the next person with the same question would skip reading that answer because of how the question is worded.
    – JaMiT
    Aug 27, 2020 at 5:12

1 Answer 1

2

You should define it as

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

BTW: The member class template Node can't use the same template parameter name T as the outer class template.

3
  • Ok that makes sense for the iterator. For the Node though should I just remove that template declaration line?
    – nick2225
    Aug 27, 2020 at 4:27
  • @nick2225 If you want it to be template itself, just change to use another template parameter name (as Iterator does). If it doesn't have to be template, just remove the line. Aug 27, 2020 at 4:28
  • @nick2225 As a non-template class, Node could use template parameter T of outer class template too. Aug 27, 2020 at 4:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.