c++ - Define friend template method outside namespace -
i have code following basic structure:
namespace a{ template<class t,unsigned dim> class cmytable{ ... public: template<class t,unsigned dim> friend std::ostream& operator<<(std::ostream& s, const cmytable<t,dim>& vec); } }; } the initial problem operator<< outside namespace a.
i tried solution : how define friends in global namespace within c++ namespace?
namespace a{ template<class t,unsigned dim> class cmytable; } template<class t,unsigned dim> std::ostream& operator<<(std::ostream& s, const cmytable<t,dim>& vec); namespace a{ template<class t,unsigned dim> class cmytable{ ... public: template<class t,unsigned dim> friend std::ostream& ::operator<<(std::ostream& s, const cmytable<t,dim>& vec); } }; } template<class t,unsigned dim> std::ostream& operator<<(std::ostream& s, const cmytable<t,dim>& vec){ // [...] } i got error : error c2063: 'operator <<' : not function inside class declaration.
public: template<class t,unsigned dim> friend std::ostream& ::operator<<(std::ostream& s, const cmytable<t,dim>& does have ideas ?
thanks.
if ostream overload has friend (needs access protected members) define inline can use template arguments passed class.
namespace a{ template<class t,unsigned dim> class cmytable{ ... public: // template<class t,unsigned dim> // shadow otherwise friend std::ostream& operator<<(std::ostream& s, const cmytable<t,dim>& vec) { // [...] } }; } otherwise remove declaration class , namesapce , define outside templated overload.
remember doesn't have friend if doesn't need access private or protected elements.
namespace a{ template<class t,unsigned dim> class cmytable{ ... public: }; } template<class t,unsigned dim> std::ostream& operator<<(std::ostream& s, const a::cmytable<t,dim>& vec){ // [...] } the third option keep friend define inside namespace a
namespace a{ template<class t,unsigned dim> class cmytable{ public: int i; template<class v,unsigned e> friend std::ostream& operator<<(std::ostream& s, const cmytable<v,e>& vec); }; }; // // namespace a{ template<class t,unsigned dim> std::ostream& operator<<(std::ostream& s, const cmytable<t,dim>& vec) { s << vec.i; } }
Comments
Post a Comment