C++ When is it OK to extend the `std` namespace?

前端 未结 2 1217
别那么骄傲
别那么骄傲 2020-12-11 19:46

A thread on SO says that extending std is UB (ok, unless you\'re the standard writers of course). But from time to time, std is happily extended. When is it OK

相关标签:
2条回答
  • 2020-12-11 19:58

    You can put template specializations for your custom data types.

    As example: your own specialzations of std::hash for std::unordered_map

    0 讨论(0)
  • 2020-12-11 20:04

    The only case where it is OK to add a definition into the std namespace is specialization of a template that already exists in the namespace and to explicitly instantiate a template. However, only if they depend on a user defined type.

    [namespace.std] (standard draft):

    1. The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

    2. The behavior of a C++ program is undefined if it declares

      (2.1) an explicit specialization of any member function of a standard library class template, or

      (2.2) an explicit specialization of any member function template of a standard library class or class template, or

      (2.3) an explicit or partial specialization of any member class template of a standard library class or class template.

      A program may explicitly instantiate a template defined in the standard library only if the declaration depends on the name of a user-defined type and the instantiation meets the standard library requirements for the original template.


    As an example of standard templates that are explicitly designed to be extended for user defined types: std::hash and std::iterator_traits.

    0 讨论(0)
提交回复
热议问题