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

2020-02-07 02:13发布

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 to do so?

2条回答
等我变得足够好
2楼-- · 2020-02-07 02:59

You can put template specializations for your custom data types.

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

查看更多
来,给爷笑一个
3楼-- · 2020-02-07 03:08

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.

查看更多
登录 后发表回答