Search code examples
c++templateslinked-listlinker-errorsfriend

Link error when using friend function in template linkedlist


I programmed a template linked list(in .h file) and I get link error.

template <typename T>
class LinkedList
{
private:
    Node<T>* head;
    Node<T>* tail;
    int size;

public:
    LinkedList();
    ~LinkedList();
    inline T* Front() {return &(this->head);};
    inline const T* Front() const {return (const T*)this->head;};
    void InsertFirst(const T&);
    void InsertLast(const T&);
    void RemoveFirst();
    void RemoveLast ();
    void RemoveItem (const T&);
    void Sort();
    void Clear();
    inline bool Exists(const T&) const;
    bool Empty() const {return this->size==0 ? true : false;};
    inline int Size() const {return this->size;};
    T* At(const int index);
    const T* At(int index) const; 
    friend ostream& operator << (ostream& out, const LinkedList<T>& that);
    T* operator[](const int);
    const T* operator[](const int) const;   
};
.
.
.

template <typename T>
ostream& operator << (ostream& out, const LinkedList<T>& that)
{
    if (!that.Empty())
        for(Node<T>* seeker=that.head; seeker; seeker=seeker->next)
            out<<seeker->info<<endl;
    return out;
}

For some reason the link error disappears when I write instead in the declaration of the friend function in the class:

template <typename T> friend ostream& operator << (ostream& out, const LinkedList<T>& that);

Solution

  • Here's the thing: the friend you declared is not a template, so the given instantiation of your << template isn't the one you declared friend.

    If you declare the friend like this

    template <typename U> //or T, doesn't matter
    friend ostream& operator << (ostream& out, const LinkedList<U>& that);
    

    then operator << <int> will be a friend of LinkedList<float>. If that is undesirable, there is this solution:

    friend ostream& operator <<<T> (ostream& out, const LinkedList<T>& that);
    

    In this case, only the particular instantiation of the template is your friend, which might be what you need.

    This article explains the topic in detail