7

The std namespace is special in C++, so ...

Is this legal C++?

// at global scope
namespace mine {
  namespace std {
    ...
  }
}

I'd call it insane, but is it allowed?

A reference (or non-reference) from the Standard would be appreciated.

Martin Ba
  • 37,187
  • 33
  • 183
  • 337
  • 1
    It seems ... unwise. `namespace mine { void foo() { using std::begin; auto it = begin(c); } }` now could behave very differently than one might expect. – Yakk - Adam Nevraumont Aug 06 '14 at 20:40
  • 1
    @Yakk in that case, you could just use `using ::std::begin;` – Drew McGowen Aug 06 '14 at 20:50
  • 2
    I don't think there's an explicit reference in the Standard, any more than there's one that says a namespace can be named `foo`. It's permitted because nothing in the Standard prohibits it. – Keith Thompson Aug 06 '14 at 21:00
  • Sigh, spent 10 minutes trying search engines when I had actually answered [a question on this matter](http://stackoverflow.com/questions/1661912/why-does-everybody-use-unanchored-namespace-declarations-i-e-std-not-std/1662052#1662052) myself 5 years ago. I need a better memory. – MSalters Aug 06 '14 at 21:11

2 Answers2

7

In the reserved names standard 17.4.3.1 (and its sub-paragraphs) I can't find anything that prohibits using std as a nested namespace name. It's not a macro, it's not in the global namespace, and it doesn't seem to meet any of the "external linkage criteria" that would prohibit it.

It appears to be legal (although as you note extremely inadvisable).

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Mark B
  • 95,107
  • 10
  • 109
  • 188
5

The rule in the standard that makes the std namespace "special" is (§17.6.4.2.1 [namespace.std]/p1):

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.

This only applies to the top level namespace.

T.C.
  • 133,968
  • 17
  • 288
  • 421
  • So, in other words, yes, it is legal C++ – Drew McGowen Aug 06 '14 at 20:51
  • 3
    That says you can't add anything with the existing namespace `std`. It doesn't directly address the question of adding a namespace named `std` within another namespace -- unless you mean that the fact that it only applies to the top level namespace implies that creating `std` elsewhere is legal. – Keith Thompson Aug 06 '14 at 20:52