Extending the std or posix Namespace

suggest change

The standard (17.6.4.2.1/1) generally forbids extending the std namespace:

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.

The same goes for 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
{
    int foo(){}
}

Nothing in the standard forbids algorithm (or one of the headers it includes) defining the same definition, and so this code would violate the One Definition Rule.

So, in general, this is forbidden. There are specific exceptions allowed, though. Perhaps most usefully, it is allowed to add specializations for user defined types. So, for example, suppose your code has

class foo
{
    // Stuff
};

Then the following is fine

namespace std
{
    template<>
    struct hash<foo>
    {
    public:
        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