7

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++.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
haipeng31
  • 635
  • 1
  • 7
  • 16

2 Answers2

7

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)
{
     ...
}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Try this :

template <typename T2> 
friend ostream &operator<< (ostream &os, const Heap<T2> &heap);

I had the same problem. Here is the question

Community
  • 1
  • 1
asheeshr
  • 4,088
  • 6
  • 31
  • 50
  • You made a small mistake, you should change "T" to "T2" in "const Heap &heap".when coming across with errors caused by template,i always have no ideas how to solve.Have you found something good for learning template? – haipeng31 Dec 01 '12 at 11:06