我正在尝试重载运算符<<作为模板类对的朋友,但我不断收到编译器警告说
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){} …Run Code Online (Sandbox Code Playgroud) 我与中描述的问题挣扎了这个问题(声明一个模板函数作为模板类的朋友),我相信第二个答案就是我想要做的(向前声明模板函数,然后将其命名一个专门为好友).我有一个问题,一个稍微不同的解决方案是否实际上是正确的,或者只是恰好在Visual C++ 2008中工作.
测试代码是:
#include <iostream>
// forward declarations
template <typename T>
class test;
template <typename T>
std::ostream& operator<<(std::ostream &out, const test<T> &t);
template <typename T>
class test {
friend std::ostream& operator<< <T>(std::ostream &out, const test<T> &t);
// alternative friend declaration
// template <typename U>
// friend std::ostream& operator<<(std::ostream &out, const test<T> &t);
// rest of class
};
template <typename T>
std::ostream& operator<<(std::ostream &out, const test<T> &t) {
// output function defined here
}
Run Code Online (Sandbox Code Playgroud)
首先,我发现一个奇怪的事情是,如果我更改前向声明operator<<以使其不匹配(例如std::ostream& …