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?
Why “using namespace std” is considered bad practice. The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type.
For example, identifiers cin and cout are defined inside the standard header file <iostream> of the namespace std. We can utilize identifiers of the std namespace in our program with:
Thus, you can refer to std entities without the std:: prefix, but it increases the probability for name conflicts, since a bunch of extra names that you didn’t expect also got added to the global namespace. std is a standard namespace that holds many C++ classes and methods like cout, cin, among others.
When we import a namespace we are essentially pulling all type definitions into the current scope. The std namespace is huge. It has hundreds of predefined identifiers, so it is possible that a developer may overlook the fact there is another definition of their intended object in the std library.
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] (standard draft):
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.
As an example of standard templates that are explicitly designed to be extended for user defined types: std::hash
and std::iterator_traits
.
You can put template specializations for your custom data types.
As example: your own specialzations of std::hash
for std::unordered_map
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With