Open In App

Nested Inline Namespaces In C++20

Last Updated : 11 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Inline Namespace is a feature that was first introduced in C++ 11. They can also be nested inside another namespace and the members of this nested namespace can be accessed as if they are the members of the parent namespace.

Their syntax may seem complex so in C++20, a new version introduced a new syntax for declaring/defining Nested Inline Namespaces which makes them more flexible and expressive.

Prerequisite: C++ Inline Namespaces, C++ Namespace Nesting.

Traditional Syntax (C++11 to C++17)

In earlier versions, the inline namespaces were defined as:

namespace my_namespace {
        inline namespace nested_namespace {
                // Members of nested_namespace
        }
}

C++20 Nested Inline Namespaces Syntax

In C++ 20, we can define the Nested Inline Namespaces like:

namespace my_namespace :: inline nested_namespace {
        // Members of nested_namespace
}

The new syntax is much easier to manage and implement.

Example

The following example demonstrates the use of the new syntax of nested inline namespaces in C++:

C++




// C++ Program to illustrate the use of new nested inline
// namespace syntax
#include <iostream>
  
namespace old_parent_ns {
    inline old_nested_ns1 {
        namespace old_nested_ns2 {
            void func() {
                std::cout << "Function from Old Defintion\n";
            }
        
    }
}
  
// declaring same namespace using new definition syntax
namespace new_parent_ns ::inline new_nested_ns1 ::
new_nested_ns2 {
    void func()
    {
        std::cout << "Function from New Definition";
    }
}
  
// driver code
int main()
{
    old_parent::old_nested_ns2::func();
    new_parent::new_nested_ns2::func();
    return 0;
}


Output

Function from Old Defintion
Function from New Definition

As we can see, both of the definition works the same. It depends upon our requirement which one we want to use.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads