我正在尝试重载operator<<类模板,如下所示:
template<int V1,int V2>
class Screen
{
template<int T1,int T2> friend ostream& operator<< (ostream &,Screen<T1,T2>&);
private:
int width;
int length;
public:
Screen():width(V1),length(V2){}
};
template<int T1,int T2>
ostream& operator<< (ostream &os,Screen<T1,T2> &screen)
{
os << screen.width << ' ' << screen.length;
return os;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码运行正确!但我想operator<<通过不将其设置为函数模板来知道是否有任何方式重载:
friend ostream& operator<< (ostream &,Screen<T1,T2>&);
?
是的,但您必须预先声明模板并使用<>语法:
template<int V1, int V2> class Screen;
template<int T1, int T2> ostream &operator<< (ostream &,Screen<T1,T2> &);
template<int V1, int V2>
class Screen
{
friend ostream& operator<< <>(ostream &, Screen&);
...
Run Code Online (Sandbox Code Playgroud)
好的做法就是有一些这样的公共功能printContent-
void Screen::printContent(ostream &os)
{
os << width << ' ' << length;
}
ostream& operator<< (ostream &os,Screen<T1,T2> &screen)
{
screen.printContent(os);
return os;
}
Run Code Online (Sandbox Code Playgroud)
因此你不需要任何friends