Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding template specialization in std namespace

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

like image 853
Mohit Jain Avatar asked Sep 23 '14 10:09

Mohit Jain


2 Answers

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.

like image 59
Angew is no longer proud of SO Avatar answered Oct 23 '22 22:10

Angew is no longer proud of SO


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.

like image 24
MSalters Avatar answered Oct 23 '22 23:10

MSalters