Overloading friend operator

You want to make one single instance (called “specialization” in generic terms) of that template a friend. You do it the following way

template <class T, class U>
class Pair{
public:
    Pair(T v1, U v2) : val1(v1), val2(v2){}
    ~Pair(){}
    Pair& operator=(const Pair&);
    friend ostream& operator<< <> (ostream&, Pair<T,U>&);

private:
    T val1;
    U val2;
};

Because the compiler knows from the parameter list that the template arguments are T and U, you don’t have to put those between <...>, so they can be left empty. Note that you have to put a declaration of operator<< above the Pair template, like the following:

template <class T, class U> class Pair;

template <class T, class U>
ostream& operator<<(ostream& out, Pair<T,U>& v);

// now the Pair template definition...

Leave a Comment