TechWiz
TechWiz

Reputation: 93

Overloading << operator on template classes

I have made a template class for a node in a linked list and I'm trying to have it output its contents to an output stream by overloading <<. However my current code:

#include <iostream>
using namespace std;
template<class NType> class Node;

template<class NType>
class Node {
private:
        void deletePointer(NType* p);
public:
        NType data;
        Node *prev, *next;

        template<typename T>
        struct is_pointer { static const bool value = false; };

        template<typename T>
        struct is_pointer<T*> { static const bool value = true; };

        Node();
        Node(NType data);
        ~Node();
};  

int main() {
        Node<int> *n1 = new Node<int>();
        Node<int> *n2 = new Node<int>(10);

        std::cout << "Node 1: " << n1 << std::endl;
        std::cout << "Node 2: " << n2 << std::endl;
}

template<class NType> inline std::ostream & operator << (std::ostream& out, const Node<NType> &node){
        out << node.data;
        return out;
}

template<class NType> inline Node<NType>::Node()
            :data(NULL), prev(NULL), next(NULL)
{
}

template<class NType> inline Node<NType>::Node(NType data)
            :data(data), prev(NULL), next(NULL)
{
}

template<class NType> inline Node<NType>::~Node(){
        if(is_pointer<NType>::value){
                deletePointer(&data);
        } else {
                return;
        }
}

template<class NType> inline void Node<NType>::deletePointer(NType* p){
    delete p;
}

Outputs memory locations rather than the data within the nodes. This happens with primitive types such as int and the like as if it didn't know what kind of data was in the NType container.

Node 1: 0x741010
Node 2: 0x741030
Node 3: 0x741070
Node 4: 0x741090

I've tried using typename rather than class but still no dice... Is there any way to dynamically find out what type the template is using and cast or something prior to insertion? I know I can make a ton of redundant code for all the primitives but that seems wasteful and unnecessary.

If it helps any, I'm compiling on Arch Linux x64 with GCC v4.6.2 20111223

Edit: Since a lot of people are mentioning it. I've also tried putting the class outside as a friend and as a stand alone function neither of which work because the stream outputs address rather than the data itself regardless of where I put it. There are no private data values to be accessed so it's OK for it to not be a friend.

Edit: Test case: http://ideone.com/a99u5 Also updated source above.

Edit: Added the remaining portion of my code to assist Aaron in his understanding of the code.

Upvotes: 8

Views: 27495

Answers (5)

Aaron McDaid
Aaron McDaid

Reputation: 27193

Others have pointed out that you need to use cout << *n1 instead of cout << n1, but there is another important bug in your code.

Your destructor includes a call deletePointer(&data); where data is a member of the class. This is dangerous. If this line of code ever was executed, then the program would probably crash. data is just one small part of the object pointed at by this, trying to delete it is like trying to delete a single element in an array is ints.

Node<int> *n1 = new Node<int>();
delete n1; // this makes sense. deleting the same thing that was new'ed

Node<int> *n1 = new Node<int>();
delete &(n1->data); // BUG

You should probably change your design a lot and simply remove the special code for pointer. Do you expect to write code like: Node<int*> *n2 = new Node<int*>( new int ); ? And if so, how do you want it to behave?

If NType actually was a pointer type, like int*, then it might make sense to do deletePointer(data), but it'll never make sense to do deletePointer(&data).

Upvotes: 0

Grizzly
Grizzly

Reputation: 20211

Your code declares the operator<< as a member function, so it would actually take the this pointer as first argument and ostream as second. Instead it needs to be a free function:

template<class NType> class Node {
public:
    NType data;
    Node *prev, *next;
};
//Note how this is declared outside of the class body, so it is a free function instead of a memberfunction
template<class NType> inline std::ostream& operator<<(std::ostream& out, const Node<NType>& val){
    out << val.data;
    return out;
}

however if your operator<< needs access to private data you need to declare it as a friend function instead:

template<class NType> class Node {
public:
    NType data;
    Node *prev, *next;
    friend std::ostream& operator<<(std::ostream& out, const Node& val){
        out << val.data;
        return out;
    }
};

Now for your output: If your operator<< was invoked the compiler would know the type of NType and do the right thing when streaming the data member. However since your operator<< should not have worked (as written) and it seems to give you memoryaddresses as output I would assume you have something like the following:

Node* n = new Node();
std::cout<<n;
//When it should be:
std::cout<<*n;

Now just for curiosity sake: Why are you implementing what looks curiously like a linked list yourself instead of simply using std::list?

Edit: Now that we can see the testcase it seems the assumptions about how the operator<< was called was correct. The output needs to be changed to:

std::cout << "Node 1: " << *n1 << std::endl;
std::cout << "Node 2: " << *n2 << std::endl;

to actually invoke the operator<< for Node, instead of the generic one for T*

Upvotes: 12

Mike DeSimone
Mike DeSimone

Reputation: 42835

You're printing the node addresses, not the nodes:

int main() {
        Node<int> *n1 = new Node<int>();
        Node<int> *n2 = new Node<int>(10);

        std::cout << "Node 1: " << n1 << std::endl;
        std::cout << "Node 2: " << n2 << std::endl;
}

n1 and n2 are pointers, not objects. You should have written:

int main() {
        Node<int> *n1 = new Node<int>();
        Node<int> *n2 = new Node<int>(10);

        std::cout << "Node 1: " << *n1 << std::endl;
        std::cout << "Node 2: " << *n2 << std::endl;
}

or:

int main() {
        Node<int> n1();
        Node<int> n2(10);

        std::cout << "Node 1: " << n1 << std::endl;
        std::cout << "Node 2: " << n2 << std::endl;
}

Upvotes: 0

Yuushi
Yuushi

Reputation: 26080

Why are you adding a template<class NType> in front of your already templated class method?

Generally, the best way of overloading operator<< is to make it a friend:

template<typename NType>
friend std::ostream& operator<<(std::ostream& out, const Node<NType>& node)
{
    out << node.data;
    return out; 
}

Edit: To respond to the comment below, this is what I mean:

When you define a class template in the header, you don't redeclare that template for the member functions of the class:

template<typename T>
class Foo
{
    T some_data;

    void member_fn();
}

This is required when you're declaring a non-member friend function, however:

template<typename NType>
class Node 
{
public:

    NType data;
    Node<NType> *prev, *next;

    //Note the different template parameter!
    template<typename NType1>
    friend std::ostream& operator<<(std::ostream& out, const Node<NType1>& node);
};

Implementation of that then becomes the above template<typename NType> std::ostream& operator<<(std::ostream& out, const Node<NType>& node) implementation.

Upvotes: 3

Tony Delroy
Tony Delroy

Reputation: 106244

template <class NType>
class Node
{
  public:
    NType data;
    Node *prev, *next;
};

template <class NType>
inline std::ostream& operator<<(std::ostream& os, const Node<NType>& n)
{
    return out << n.data;
}

Upvotes: 1

Related Questions