Where should non-member operator overloads be placed?

前端 未结 3 1326
一整个雨季
一整个雨季 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:08

    Don't add it to the std namespace, place it in the same namespace as your class. The purpose of a namespace is to prevent collisions. The standard says

    17.4.3.1 Reserved names

    It is undefined for a C++ program to add declarations or definitions to namespace std or namespaces within namespace std unless otherwise specified. A program may add template specializations for any standard library template to namespace std. Such a specialization (complete or partial) of a standard library template results in undefined behavior unless the declaration depends on a user-defined name of external linkage and unless the specialization meets the standard library requirements for the original template.

提交回复
热议问题