Extending the std or posix Namespace

suggest change

N3690, a 2013 working draft, states (17.6.4.2.1/1) that extending namespace std is undefined unless a rule allows it. Later standards keep this rule for std:

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.

That draft says the same about namespace posix (17.6.4.2.2/1):

The behavior of a C++ program is undefined if it adds declarations or definitions to namespace posix or to a namespace within namespace posix unless otherwise specified.

Consider the following:

#include <algorithm>

namespace std
{
    void foo() {}
}

That rule already makes the program undefined. A header such as <algorithm> might also declare foo, which would break the One Definition Rule.

There are specific exceptions. A program may specialize a standard library template for a program-defined type when the specialization meets that template’s requirements. std::hash is a common case, and it is C++11. Suppose the program has:

class foo
{
    // Stuff
};

Then the following is fine:

#include <functional>

namespace std
{
    template<>
    struct hash<foo>
    {
    public:
        std::size_t operator()(const foo &f) const;
    };
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents