HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

C++ Node class template

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
nodeclasstemplate

Problem

I'm working on building understanding of data structures in general, and specifically linked lists in this example. I'm also trying to increase my ability with templates.

In cross-referencing dozens of examples, I've blended what I've seen into the following node template "Node.h" file:

/*
11 May 2015
VS 2015 Community
Author: Diche Bach
Node template header file.
*/
#ifndef NODE_H
#define NODE_H

#include

template
class Node
{
    friend std::istream& operator>>(std::istream& str, tNode& data)
    {
        return str >> data_;
    }
    friend std::ostream& operator<<(std::ostream& str, tNode const& data)
    {
        return str << data_ << " ";
    }
    public:
      Node(tNode data, tNode *link);

    private:
      tNode data;
      tNode *next;
};

#endif /* NODE_H */


The goal is that this Node template be as modular and 'resusable' as possible. Thus, the same node template could be used with a LinkedList template, a DoubleLinked List template, a Stack template, etc.

With only two semesters of C++ under my belt, I'm pushing my envelope, and I appreciate suggestions and comments.

The use of the friend mechanism is something I've never done before, but it seems salient to the goals, so I particularly appreciate comments on that portion.

Solution

In the case of linked lists, the pointer to the next value should be a pointer to another Node instance, not a pointer to another data entry. This would allow you to walk the entire list node-by-node.

You have defined methods for using a stream to read/write the node's value, but what if I just want to access the value do something else with it that doesn't involve a stream? A getter like T& getValue(); and/or const T& getValue() const should be mandatory. This will also allow you to extract the stream operators outside of the class and be able to implement them without friend.

When it comes to templates T is preferred as the typename insteam of tNode which can be easily mistaken for a specific class instead of a template.

Context

StackExchange Code Review Q#128106, answer score: 4

Revisions (0)

No revisions yet.