An inline namespace is a nested namespace whose members can be accessed as if they belonged to the enclosing namespace. It is commonly used for library versioning and reducing namespace qualification.
- Makes members of a nested namespace directly accessible through the enclosing namespace.
- Helps simplify namespace usage and supports library versioning.
#include <iostream>
using namespace std;
namespace ns1 {
inline namespace ns2 {
int var = 10;
}
} // namespace ns1
int main()
{
cout << ns1::var;
return 0;
}
Output
10
Explanation
- ns2 is declared as an inline namespace inside ns1.
- Therefore, var can be accessed directly as ns1::var.
- It is equivalent to writing ns1::ns2::var.
Syntax
inline namespace namespace_name{
// declarations
}
Nested Inline Namespaces
Inline namespaces can be nested. The members of the innermost inline namespace are also accessible through the outer namespaces.
#include <iostream>
using namespace std;
namespace ns1 {
inline namespace ns2 {
inline namespace ns3 {
int var = 10;
}
} // namespace ns2
} // namespace ns1
int main()
{
cout << ns1::var;
return 0;
}
Output
10
Explanation
- ns3 is an inline namespace inside another inline namespace (ns2).
- Therefore, var can be accessed through ns1 without specifying ns2 or ns3.
Advantages of Inline Namespaces
Inline namespaces provide several benefits:
- Reduce long namespace qualifications.
- Improve code readability.
- Support library versioning while maintaining backward compatibility.
- Allow newer library versions to become the default without changing existing code.
Using Directive Inside Namespaces
A similar effect can be achieved by importing a nested namespace using the using directive.
Syntax
using namespace namespace_name;
#include <iostream>
using namespace std;
namespace ns1 {
namespace ns2 {
namespace ns3 {
int var = 10;
}
using namespace ns3;
} // namespace ns2
using namespace ns2;
} // namespace ns1
int main()
{
cout << ns1::var;
return 0;
}
Output
10
Explanation
- using namespace ns3; makes the members of ns3 visible inside ns2.
- using namespace ns2; makes those members visible inside ns1.
- As a result, var can be accessed as ns1::var.
Inline Namespace vs Using Directive
| Feature | Inline Namespace | Using Directive |
|---|---|---|
| Purpose | Makes nested namespace members part of the enclosing namespace | Imports names from another namespace into the current scope |
| Intended Use | Library versioning and API evolution | Simplifying namespace access |
| Automatic Visibility | Yes | No, requires an explicit using declaration |
| Recommended For | Versioned libraries | General namespace convenience |