Adding template specialization in std namespace

2020-06-21 03:40发布

Background:
I tried to answer the question Why isn't my overloading < operator not working for STL sort. One of my suggestion (apart from using predicate) was to move the custom operator < for std::string in namespace std so that it can be preferred by the compiler over templated version.

At lightening speed the answer was down-voted with following comment from a highly reputed user:

This is undefined behaviour, you are not allowed to add declarations to namespace std because it can change the behaviour of the standard library componens

My Question:
Is it okay to add template specialization for stl types even if the declaration of this specialization doesn't contain user defined data type?


p.s. I have deleted my answer as I am afraid it may be possibly wrong

4条回答
Ridiculous、
2楼-- · 2020-06-21 04:06

Standard Library is flexible enough, having many extra params for allocators, predicates etc. So that, if you're about to add something to std namespace, it seems you pursuit your goals via the wrong way.

Take a rest to switch your mind, then read STL sources and play conform with it.

查看更多
Deceive 欺骗
3楼-- · 2020-06-21 04:17

Angew got the relevant quote, but the interpretation is flawed.

You propose to add a template specialization in namespace std. This is permitted only if it depends on a user-defined type. You specifically mention that it does not. Therefore, the preconditions for the exception are not met, and the basic rule (no additions) applies. Not OK.

查看更多
Deceive 欺骗
4楼-- · 2020-06-21 04:17

STL classes are meant to be used in well-defined ways, i.e. either instantiate them with a POD type, or a STL class that conforms to the class's requirements, or a user-defined type that implements the class's requirements.

You're not supposed to inherit from STL types either; it's better to create a new class with the STL object as a member; then you can implement public methods matching the STL object's method signature.

Without going into all the rationale for this rules, this is the most portable and likely long-lived way to use STL classes. It keeps a bright line between application-specific classes and STL classes.

查看更多
Anthone
5楼-- · 2020-06-21 04:27

C++11, [namespace.std]§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.

The above paragraph explcitily prohibits specialisations which do not depend on a user-defined type.

As to the motivation: you wouldn't be adding a template specialisation, but a separate declaration, which is also prohibited.

查看更多
登录 后发表回答