重载friend operator <<为模板类

tri*_*ker 28 c++ operators

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

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

对于此代码:

friend ostream& operator<<(ostream&, Pair<T,U>&);
Run Code Online (Sandbox Code Playgroud)

作为推荐说,它给出了第二个警告

if this is not what you intended, make sure the function template has already been declared and add <> after the function name here
Run Code Online (Sandbox Code Playgroud)

这是函数定义

template <class T, class U>
ostream& operator<<(ostream& out, Pair<T,U>& v)
{
    out << v.val1 << " " << v.val2;
}
Run Code Online (Sandbox Code Playgroud)

这是整个班级.

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;
};
Run Code Online (Sandbox Code Playgroud)

我不知道从推荐警告中得到什么,除此之外我可能必须在朋友声明中放置一些内容.有谁知道这个的正确语法?谢谢.

Joh*_*itb 46

您希望将该模板的一个实例(在通用术语中称为"专业化")作为朋友.你这样做的方式如下

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;
};
Run Code Online (Sandbox Code Playgroud)

因为编译器从参数列表中知道模板参数是,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...
Run Code Online (Sandbox Code Playgroud)

  • +1这实际上是编译器所抱怨的.另一个答案用一个解决方法处理问题:它不是告诉编译器朋友是模板的特化,而是为给定类型创建一个非模板化的operator <<函数. (11认同)
  • 哇,额外的`&lt;&gt;`很容易被忽略! (2认同)

Asi*_*sik 20

您将operator <<声明为返回ostream&,但该方法中根本没有return语句.应该:

template <class T, class U>
ostream& operator<<(ostream& out, Pair<T,U>& v)
{
    return out << v.val1 << " " << v.val2;
}
Run Code Online (Sandbox Code Playgroud)

除此之外,我没有任何问题或警告在Visual Studio 2008下编译你的代码,并在第4级发出警告.哦,有经典的链接器错误,但是通过将模板函数定义移动到类声明中可以很容易地绕过它,如所解释的那样在C++ FAQ中.

我的测试代码:

#include <iostream>
using namespace std;

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& out, Pair<T,U>& v)
    {
        return out << v.val1 << " " << v.val2;
    }
private:    
    T val1;
    U val2;
};

int main() {
    Pair<int, int> a(3, 4);
    cout << a;      
}
Run Code Online (Sandbox Code Playgroud)