Adding template specialization in the std namespace

Background:
I tried to answer the question Why is my overload <statement not working for STL sorting . One of my suggestions (besides using the predicate) was to move the user operator < for std::string in the std namespace so that it could be preferred by the compiler over the template version.

At lighting speed, the answer was voted by the following comment from a senior user:

This behavior is undefined, you are not allowed to add declarations to the std namespace, as it can change the behavior of the standard componentens library

My question is:
Is it possible to add a template specialization for stl types even if the declaration of this specialization does not contain a custom data type?


ps I deleted my answer as I am afraid this might be wrong.

+5
source share
4 answers

C ++ 11, [namespace.std] ยง1:

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

In the paragraph above, specialization is strictly prohibited, which does not depend on the type defined by the user.

As for motivation: you would not add specialization to the template, but a separate declaration, which is also prohibited.

+12
source

The angel received the appropriate quote, but the interpretation is erroneous.

You suggest adding a specialization pattern to namespace std . This is only allowed if it depends on the user type. You specifically mention that this is not the case. Therefore, the prerequisites for exclusion are not fulfilled, and the basic rule is applied (without additions). Not okay.

+5
source

The standard library is quite flexible, with many additional parameters for distributors, predicates, etc. So, if you are going to add something to the std namespace, it seems that you are pursuing your goals out of the way.

Take a break to switch your mind, then read the STL sources and combine the game.

+1
source

STL classes are intended for use in well-defined ways, that is, they either create them using the POD type, or an STL class that meets the class requirements, or a user-defined type that implements class requirements.

You should also not inherit from STL types; it is better to create a new class with an STL object as a member; then you can implement public methods that correspond to the method signature of the STL object.

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

0
source

Source: https://habr.com/ru/post/1203203/


All Articles