[英]how to overload << operator of class template with non-type parameter?
I'm trying to overload operator<<
of a class template , like this: 我正在尝试重载类模板的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;
}
the code above is running corrent!but i want to know if there is any way to overload operator<<
in a way by not setting it as a function template: 上面的代码运行正确!但我想知道是否有任何方法通过不将它设置为函数模板来重载operator<<
:
friend ostream& operator<< (ostream &,Screen<T1,T2>&);
? ?
Yes, but you have to predeclare the template and use <>
syntax: 是的,但您必须预先声明模板并使用<>
语法:
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&);
...
Good practice is to have some public function printContent
like this - 好的做法是有一些像这样的公共功能printContent
-
void Screen::printContent(ostream &os)
{
os << width << ' ' << length;
}
ostream& operator<< (ostream &os,Screen<T1,T2> &screen)
{
screen.printContent(os);
return os;
}
thus you don't need any friend
s 因此你不需要任何friend
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.