How to overload << class template operator with non-type parameter?

I am trying to overload operator<< class template, for example:

 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 above code launches corrent !, but I want to know if there is a way to overload operator<< in a sense without setting it as a function template:

friend ostream& operator<< (ostream &,Screen<T1,T2>&);

+6
source share
2 answers

Yes, but you must provide a pattern and use the <> 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&); ... 
+6
source

It is good practice to have some public printContent function like this -

 void Screen::printContent(ostream &os) { os << width << ' ' << length; } ostream& operator<< (ostream &os,Screen<T1,T2> &screen) { screen.printContent(os); return os; } 

so you don't need friend s

+5
source

All Articles