为模板类重载好友运算符<<

我正在尝试将运算符<<作为模板类Pair的朋友重载,但我不断收到编译器警告说


friend declaration std::ostream& operator<<(ostream& out, Pair<T,U>& v) declares a non template function

对于此代码:


friend ostream& operator<<(ostream&, Pair<T,U>&);

它给出第二条警告作为建议说


if this is not what you intended, make sure the function template has already been declared and add <> after the function name here

这是功能定义


template <class T, class U>

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

{

    out << v.val1 << " " << v.val2;

}

这是全班。


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;

};

我不确定从推荐警告中可以得出什么,除了我可能必须在朋友声明中放置某处之外。有谁知道正确的语法吗?谢谢。


一只名叫tom的猫
浏览 500回答 3
3回答

守着一只汪

您希望使该模板的一个实例(一般称为“专业化”)成为朋友。您可以通过以下方式进行template <class T, class U>class Pair{public:&nbsp; &nbsp; Pair(T v1, U v2) : val1(v1), val2(v2){}&nbsp; &nbsp; ~Pair(){}&nbsp; &nbsp; Pair& operator=(const Pair&);&nbsp; &nbsp; friend ostream& operator<< <> (ostream&, Pair<T,U>&);private:&nbsp; &nbsp; T val1;&nbsp; &nbsp; U val2;};因为编译器从参数列表中知道模板参数是T和U,所以您不必将<...>它们放在之间,因此可以将其保留为空。请注意,您必须operator<<在Pair模板上方放置一个声明,如下所示: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...

jeck猫

简单的内联版本:template<typename T> class HasFriend {&nbsp; &nbsp; private:&nbsp; &nbsp; &nbsp; &nbsp; T item;&nbsp; &nbsp; public:&nbsp; &nbsp; &nbsp; &nbsp;~HasFriend() {}&nbsp; &nbsp; &nbsp; &nbsp;HasFriend(const T &i) : item(i) {}&nbsp; &nbsp; friend ostream& operator<<(ostream& os, const HasFriend<T>& x) {&nbsp; &nbsp; &nbsp; &nbsp; return os << "s(" << sizeof(x) << ").op<<" << x.item << endl;&nbsp; &nbsp; }};修改后的模板版本:template<template<typename /**/> class U, typename V>ostream& operator<<(ostream &os, const U<V> &x) {&nbsp; &nbsp; return os << "s(" << sizeof(x) << ").op<<" << x.item << endl;}template<typename T> class HasFriend {&nbsp; &nbsp; private:&nbsp; &nbsp; &nbsp; &nbsp; T item;&nbsp; &nbsp; public:&nbsp; &nbsp; &nbsp; &nbsp;~HasFriend() {}&nbsp; &nbsp; &nbsp; &nbsp;HasFriend(const T &i) : item(i) {}&nbsp; &nbsp; friend ostream& operator<<<>(ostream&, const HasFriend<T>&);};
打开App,查看更多内容
随时随地看视频慕课网APP