Where should non-member operator overloads be placed?

前端 未结 3 1325
一整个雨季
一整个雨季 2020-12-01 23:57

I want to overload operator<< for my class. Should I add this overloaded definition to the std namespace? (since the ostream operator&l

3条回答
  •  悲哀的现实
    2020-12-02 00:12

    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.

提交回复
热议问题