[c++] Inline namespaces

In C++, inline namespaces were introduced in the C++11 standard to provide a way to organize and version namespaces. This feature allows for the creation of clear and concise code by reducing the need for nested namespaces and eliminating repetitive namespace specifications.

Declaration and Usage

To declare an inline namespace, the inline keyword is used followed by the namespace declaration. Here’s an example:

namespace A
{
    inline namespace B
    {
        void foo() { /* ... */ }
    }
}

The inline namespace B is nested within the namespace A. When using the members of namespace B, there is no need to explicitly specify the B namespace. For example, the function foo can be called directly as A::foo().

Versioning and Backward Compatibility

Inline namespaces are commonly used for versioning library APIs. By using an inline namespace, code that requires an older version of the library can directly access it without the need for explicit name qualification. Meanwhile, the newest version of the library can be easily referred to.

Benefits

Conclusion

Inline namespaces in C++ provide an efficient way to organize code and manage versions, making it easier to maintain and develop software libraries.

For more details, please refer to the C++ standard.


Keywords

C++, inline namespaces

References

A Tour of C++ (2nd Edition) by Bjarne Stroustrup