正常
Nested Namespaces (C++17)
In a Nutshell
Use the single line namespace A::B::C { ... } in place of three layers of nested braces—pure syntactic sugar, yet it greatly reduces indentation levels.
Header
None (language feature)
Core API Cheat Sheet
| Syntax | Equivalent Form |
|---|---|
namespace A::B { ... } | namespace A { namespace B { ... } } |
namespace A::B::C { ... } | namespace A { namespace B { namespace C { ... } } } |
namespace A::inline B { ... } | namespace A { inline namespace B { ... } } (C++20) |
Minimal Example
C++
// Standard: C++17
#include <iostream>
// Nested namespace definition
namespace hardware::spi {
void init() { std::cout << "SPI init\n"; }
}
// Equivalent C++11 style (exactly the same effect)
namespace hardware {
namespace i2c {
void init() { std::cout << "I2C init\n"; }
}
}
int main() {
hardware::spi::init(); // SPI init
hardware::i2c::init(); // I2C init
}Embedded Applicability: Low
- Pure syntactic sugar that does not affect the generated code, and embedded projects usually do not have deep namespace hierarchies.
- Helpful for organizing code in large libraries and drivers, reducing indentation nesting.
- Embedded code often uses flatter namespaces (e.g.,
bsp::,hal::), where a single level is enough. - 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 referenced from cppreference.com, licensed under CC-BY-SA 4.0