c++ - Where should non-member operator overloads be placed? -


i want overload operator<< class. should add overloaded definition std namespace? (since ostream operator<< part of std namespace) or should leave in global namespace?

in short:

class myclass {  };  namespace std {     ostream& operator<< ( ostream& ostr, const myclass& mytype ) {} } 

or

class myclass {  };  std::ostream& operator<< ( std::ostream& ostr, const myclass& mytype ) {} 

which more appropriate , why? in advance responses.

you should put operator overload in same namespace class.

this allow operator found during overload resolution using argument-dependent lookup (well, actually, since ostream in namespace std, overload overload found if put in namespace std, there no reason that).

from point of view of design practices, operator overload more part of class's interface interface of ostream, belongs in same namespace class (see herb sutter's namespaces , interface principle).

from point of view of writing standards-compliant , portable code, can't put operator overload namespace std. while can add template specializations user-defined entities namespace std, can't add additional function overloads.


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -