Where should non-member operator overloads be placed?

You should put the operator overload in the same namespace as your class.

This will allow the operator to be found during overload resolution using argument-dependent lookup (well, actually, since ostream is in namespace std, the overload overload would also be found if you put it in namespace std, but there is no reason to do that).

From the point of view of good design practices, the operator overload is more a part of your class’s interface than the interface of ostream, so it belongs in the same namespace as your class (see also Herb Sutter’s Namespaces and the Interface Principle).

From the point of view of writing standards-compliant and portable code, you can’t put the operator overload into namespace std. While you can add template specializations for user-defined entities to namespace std, you can’t add additional function overloads.

Leave a Comment