I am trying to implement a generic linked list and linked list iterator in C++. I have a node struct as follows
template <typename T>
struct Node
{
T m_data;
Node<T>* m_next;
};
I also have a linked list iterator that is a template so it can generate both regular and const
iterators.
template <typename NodeType>
class LinkedListIterator
{
private:
NodeType* m_node;
public:
LinkedListIterator(NodeType* n);
T& operator*() const;
};
My question is how do I properly declare the operator*()
function? My expectation is that something like the following should work
LinkedListIterator<const Node<T>> my_iter(some_node_pointer);
*my_iter = new_value; // should not work
I understand that returning T
in the operator*()
does not make sense since this class does not have access to the typename in the Node
class.
I found a work around by creating an alias to the type inside the Node
class like so
template <typename T>
struct Node
{
typedef T type_value;
// rest of Node class...
};
and now I can do the following in my iterator class
template <typename NodeType>
class LinkedListIterator
{
public:
typename NodeType::type_value& operator*() const;
};
This seems to work and will return the right value. So my question really should be, is this the best way to implement this? Do I need to have typedef
to create an alias so that I can use that type? Or is there a way to determine the type inside the LinkedListIterator
class?