Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

c++ - 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;
};

I wasn't sure what to draw from the recommendation warning, other than that maybe I have to put somewhere in the friend declaration. Does anyone know the proper syntax for this? Thanks.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...