Is there a specific reason nested namespace declarations are not allowed in C++?
The standard does not allow code like this:
namespace Hello::World {
//Things that are in namespace Hello::World
}
and instead requires
namespace Hello { namespace World {
//Things that are in namespace Hello::World
}}
What is the rationale? Was this simply not thought of at the 开发者_StackOverflowtime, or is there a specific reason it is not included?
It seems that the first syntax more directly expresses in which namespace one is supposed to be, as the declaration mimics the actual use of the namespace in later code. It also results in less indentation if you are unfortunate enough to be using a "dumb" bracket counting indentation tool.
The reason is most likely "because that's how the language evolved."
There has been at least one proposal ("Nested Namespace Definition Proposal" in 2003) to allow nested namespace definitions, but it was not selected for inclusion in C++0x.
Nested namespace definition is part of the C++17 working draft.
This topic is mentioned in the proposal as an example of this feature being a programmers' demand original n4026 updated version: n4230.
Current latest draft: n4567 (paragraph 7.3.1 item 10)
7.3.1 Namespace Definition
...
10 A nested-namespace-definition with an enclosing-namespace-specifier E, identifier I and namespace-body B is equivalent tonamespace E { namespace I { B } }
Example:
namespace A::B::C { int i; } The above has the same effect as: namespace A { namespace B { namespace C { int i; } } }
Compiler Support
GCC since version 6 enable using -std=c++1z
Visual C++ since 2015 update 3 enable using /std:c++latest
Clang since version 3.6 enable using -std=c++1z
I presume you'd rather want it to be so that, given namespace X::Y
, it should be equivalent to "namespace X { namespace Y`. Which sounds fine on the surface of it, but consider a corner case:
namespace Hello {
namespace {
namespace World {}
}
}
// Does this refer to an existing namespace? Or does it define a new one?
namespace Hello::World {}
In C++ qualified names are reserved for referring to previously declared entities. This applies to both "sources" of qualified names: classes and namespaces.
I think it was a design choice.
The first syntax looks good. I would want to have it too. However, the second one is more structured. You don't create nested namespaces this way:
Hello::World::Everyone::Great {
}
Will you declare this beforehand?
精彩评论