Extending the namespace std
From cppreference.com
Adding declarations to std
It is undefined behavior to add declarations or definitions to namespace std or to any namespace nested within std, with a few exceptions noted below.
#include <utility>
namespace std
{
// a function definition added to namespace std: undefined behavior
pair<int, int> operator+(pair<int, int> a, pair<int, int> b)
{
return {a.first + b.first, a.second + b.second};
}
}
Adding template specializations
Class templates
It is allowed to add template specializations for any standard library class template to the namespace std only if the declaration depends on at least one program-defined type and the specialization satisfies all requirements for the original template, except where such specializations are prohibited.
// Get the declaration of the primary std::hash template.
// We are not permitted to declare it ourselves.
// <typeindex> is guaranteed to provide such a declaration,
// and is much cheaper to include than <functional>.
#include <typeindex>
// Specialize std::hash so that MyType can be used as a key in
// std::unordered_set and std::unordered_map. Opening namespace
// std can accidentally introduce undefined behavior, and is not
// necessary for specializing class templates.
template<>
struct std::hash<MyType>
{
std::size_t operator()(const MyType& t) const { return t.hash(); }
};
- Specializing the template std::complex for any type other than
float,double, andlong doubleis unspecified.
- Specializations of std::numeric_limits must define all members declared
static const(until C++11)static constexpr(since C++11) in the primary template, in such a way that they are usable as integral constant expressions.
|