Don't reopen `namespace std` – Arthur O'Dwyer – Stuff mostly about C++

submited by
Style Pass
2021-10-27 19:30:10

Today (in two different contexts) I saw people reopening namespace std in order to introduce a partial specialization of a standard template. For example:

Also, by keeping all parts of the qualified name together in the source code, it’s easier to see that what we’re doing here is specializing std::hash — not just hash. Explicit is good.

This works in isolation, but watch what happens after I #include <valarray> (perhaps transitively, from another header):

Outside namespace std, the name slice refers to ::slice; but inside the namespace, it refers to std::slice, an obscure utility type associated with std::valarray. To work around this, we could cruft up our template specialization a little more:

However, you should still be aware that if you’re specializing a class template like std::hash — or anything that requires you to type curly braces — then everything inside the curly braces is still considered “inside” namespace std for the purposes of name lookup. (Godbolt.)

So, sometimes it can still be necessary to ::-qualify names inside the curly braces. This is highly unfortunate, and I’m not aware of any simple workaround. (But most names won’t collide with anything in the standard library. If you run into a scenario requiring ::-qualification in real-world code, I’d be interested to hear about it!)

Leave a Comment