C ++什么时候可以扩展`std`名称空间? [英] C++ When is it OK to extend the `std` namespace?

查看:81
本文介绍了C ++什么时候可以扩展`std`名称空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个关于SO的线程说

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?

推荐答案

唯一可以在std命名空间中添加定义的情况是命名空间中已经存在的模板的特化并显式实例化模板.但是,只有它们取决于用户定义的类型.

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] (标准草案):

  1. 如果C ++程序的声明或定义添加到名称空间std或名称空间std中的名称空间中,则C ++程序的行为是不确定的,除非另有说明.

  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.

如果声明,则C ++程序的行为是不确定的

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

(2.1)标准库类模板的任何成员函数的显式专业化,或者

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

(2.2)标准库类或类模板的任何成员函数模板的显式专业化,或

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

(2.3)对标准库类或类模板的任何成员类模板进行显式或部分专业化.

(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::hashstd::iterator_traits.

这篇关于C ++什么时候可以扩展`std`名称空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆