'C++ multiple nested template types inside outer template class referring to each other
I am quite new to C++ and I am trying to code a simple version of a list (doubly linked as in STL). The list has a template parameter. Inside the list I define two nested classes, also with different template parameters. Now, I agree, in this case defining the inner classes as templates is completely useless because their use is to the outer class template type; but this for me an intellectual exercise more than anything else, to learn more about C++. With that said, I am trying to define member functions outside the scope of the class. My IDE says that the prototype for the Iterator constructor inside the NodeList class with argument does not match my definition.
So first of all, the type is not recognized and why is that happening. Secondly, how do I achieve what I am trying to do?
Thanks a lot in advance
template <typename T>
class NodeList
{
typedef T value_type;
public:
template <typename E>
class Iterator
{
template <typename> friend class NodeList;
public:
E& operator*();
bool operator==(const Iterator&) const;
bool operator!=(const Iterator&) const;
Iterator& operator++();
Iterator operator++(int);
Iterator& operator--();
Iterator operator--(int);
private:
NodeList<E>::Node<E> *node;
Iterator(NodeList<E>::Node<E> *node);
};
private:
template <typename E = value_type> struct Node
{
E element;
Node<E> *prev;
Node<E> *next;
};
};
template <typename T>
template<typename E>
NodeList<T>::Iterator<E>::Iterator(NodeList<T>::Node<E> *node)
{
}
Solution 1:[1]
Two things wrong with that code:
1 You can't use Node before it is declared. So move that private block up top.
2 NodeList<E>::Node<E> must be NodeList<T>::Node<E>, or simply Node<E> as you are already in the Nodelist<T> class.
template <typename T>
class NodeList
{
typedef T value_type;
template <typename E = value_type> struct Node
{
E element;
Node<E> *prev;
Node<E> *next;
};
public:
template <typename E>
class Iterator
{
template <typename> friend class NodeList;
public:
E& operator*();
bool operator==(const Iterator&) const;
bool operator!=(const Iterator&) const;
Iterator& operator++();
Iterator operator++(int);
Iterator& operator--();
Iterator operator--(int);
private:
Node<E> *node;
Iterator(Node<E> *node);
};
};
template <typename T>
template <typename E>
NodeList<T>::Iterator<E>::Iterator(NodeList<T>::Node<E> *node)
{
}
I can think of cases where a Nodelist<E>::Node<E> could be a desired in the subclass or even the class itself but that either needs a different syntax or maybe isn't even supported. But I think in this case Nodelist<T>::Node<E> is actually the desired type.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Goswin von Brederlow |
