正常
Nested Namespaces (C++17)
The Gist
Use namespace A::B::C to replace three layers of nested braces—pure syntactic sugar that drastically reduces indentation levels.
Header
None (language feature)
Core API Cheat Sheet
| Syntax | Equivalent |
|---|---|
namespace A::B::C { ... } | namespace A { namespace B { namespace C { ... } } } |
namespace A::B::C::D { ... } | namespace A { namespace B { namespace C { namespace D { ... } } } } |
namespace A::B { inline namespace C { ... } } | namespace A { namespace B { inline namespace C { ... } } } (C++20) |
Minimal Example
cpp
// C++17 style: concise and flat
namespace App::Hardware::Driver {
void init() {
// Initialization logic
}
}
// Traditional C++ style: verbose and deeply indented
namespace App {
namespace Hardware {
namespace Driver {
void init() {
// Initialization logic
}
}
}
}Embedded Applicability: Low
- Pure syntactic sugar; it does not affect generated code, but embedded projects typically do not have deep namespace hierarchies.
- Helpful for organizing code in large libraries and drivers by reducing indentation nesting.
- Embedded code often uses flatter namespaces (e.g.,
HAL,Driver), where a single level is sufficient. - Universally supported by C++17 compilers with no compatibility concerns.
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| 7 | 3.9 | 19.1 |
See Also
Part of the content references cppreference.com, licensed under CC-BY-SA 4.0