[c++] Inline namespaces

In C++, an inline namespace is a way to extend and organize namespaces while providing backward compatibility.

What is an inline namespace?

An inline namespace is a feature introduced in C++11 that allows for the creation of a new namespace that is a direct extension of an existing namespace. It can be used to version namespaces without breaking existing code.

How to use an inline namespace

To define an inline namespace, you can use the inline keyword followed by the namespace definition:

namespace version1 {
    void function1() {
        // Implementation for version 1
    }
}

inline namespace version2 {
    void function1() {
        // New implementation for version 2
    }
}

In this example, version2 is an inline namespace that extends version1. The inline keyword specifies that version2 is an inline namespace, and it will be treated as part of version1.

Benefits of using inline namespaces

Using inline namespaces provides several benefits:

Example usage

namespace mylib {
    void function1() {
        // Implementation in mylib
    }

    inline namespace v2 {
        void function1() {
            // New implementation for v2
        }
    }
}

In this example, the mylib::function1() is extended with a new implementation in the v2 inline namespace.

Conclusion

Inline namespaces offer a convenient way to introduce new versions or variations of code in C++ without breaking existing code. They are a powerful tool for managing backward compatibility and organizing code within namespaces.

For more information, refer to the C++ reference for inline namespaces.