Algorithm

11 Apr 2012

Overloading friend operator for template class

I'm trying to overload the operator << as a friend to a template class Pair, but I keep getting a compiler warning saying----

friend declaration std::ostream& operator<<(ostream& out, Pair<T,U>& v) declares a non template function
for this code:
friend ostream& operator<<(ostream&, Pair<T,U>&);
it gives a second warning as a recommendation saying
if this is not what you intended, make sure the function template has already been declared and add <> after the function name here
Here is the function definition
template <class T, class U>
ostream& operator<<(ostream& out, Pair<T,U>& v)
{
    out << v.val1 << " " << v.val2;
}
and here is the whole class.
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;
};

Tidak ada komentar:

Posting Komentar