Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined reference to friend function in template class

Tags:

c++

templates

The following codes are in file Heap.h

    template <typename T>
    class Heap {
    public:
         Heap();
         Heap(vector<T> &vec);
         void insert(const T &value);
         T extract();
         T min();
         void update(int index, const T &value);

         /* for debug */
         friend ostream &operator<< (ostream &os, const Heap<T> &heap);
         #if 0
         {
            for (int i = 0; i < heap.vec_.size(); i++) {
                 os << heap.vec_[i] << " ";
            }

            return os;
         }
         #endif

         private:
          void minHeapify(int index);
          int left(int index);
          int right(int index);
          int parent(int index);
          void swap(int, int);
          vector<T> vec_;
    };

    template <typename T>
    ostream &operator<<(ostream &os, const Heap<T> &heap)
    {
        for (int i = 0; i < heap.vec_.size(); i++) {
            os << heap.vec_[i];
        }

        return os;
    }

In a testheap.cpp file, I use this template class, when I compile, an undefined reference to the << operator overloading function error occur. Confused with this situation. When I put the definition of the function in the class, it works. The OS is Ubuntu, compiler is g++.

like image 422
haipeng31 Avatar asked Dec 01 '12 09:12

haipeng31


1 Answers

The following should work:

template <typename T>
class Heap {
public:
     ...
     template<class U>
     friend ostream &operator<<(ostream &os, const Heap<U> &heap);
     ...
};

template <typename T>
ostream &operator<<(ostream &os, const Heap<T> &heap)
{
     ...
}
like image 109
NPE Avatar answered Nov 12 '22 19:11

NPE