C++ 什么时候可以扩展 std 命名空间?
C++ When is it OK to extend the `std` namespace?
SO 上的一个线程说 (好吧,当然除非你是标准的作家)。但时不时地,std
会愉快地延长。什么时候可以这样做?
您可以为您的自定义数据类型设置模板专业化。
例如:您自己的 std::hash
专业化 std::unordered_map
唯一可以将定义添加到 std
命名空间的情况是对已存在于命名空间中的模板进行专门化并显式实例化模板。但是,仅当它们依赖于用户定义的类型时。
[namespace.std](标准稿):
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.
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.
作为明确设计用于扩展用户定义类型的标准模板的示例:std::hash
和 std::iterator_traits
。
SO 上的一个线程说 std
会愉快地延长。什么时候可以这样做?
您可以为您的自定义数据类型设置模板专业化。
例如:您自己的 std::hash
专业化 std::unordered_map
唯一可以将定义添加到 std
命名空间的情况是对已存在于命名空间中的模板进行专门化并显式实例化模板。但是,仅当它们依赖于用户定义的类型时。
[namespace.std](标准稿):
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.
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.
作为明确设计用于扩展用户定义类型的标准模板的示例:std::hash
和 std::iterator_traits
。