Skip to content

Nested Namespaces (C++17)

In a Nutshell

Replace three levels of nested braces with a single namespace A::B::C { ... } line -- pure syntactic sugar, but it dramatically reduces indentation depth.

None (language feature)

Core API Quick Reference

SyntaxEquivalent
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

cpp
// Standard: C++17
#include <iostream>

// Nested namespace definition
namespace hardware::spi {
    void init() { std::cout << "SPI init\n"; }
}

// Equivalent C++11 style (identical 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 generated code; however, embedded projects typically do not have deep namespace hierarchies
  • Helpful for organizing large libraries and drivers, reducing nesting indentation
  • Embedded code often uses flat namespaces (e.g., bsp::, hal::) where a single level suffices
  • Universally supported by C++17 compilers with no compatibility concerns

Compiler Support

GCCClangMSVC
73.919.1

See Also


Some content adapted from cppreference.com under CC-BY-SA 4.0 license

Built with VitePress