
C++11 standard allows the inline keyword in a namespace-definition. An inline namespace is a namespace that uses the optional keyword inline in its original-namespace-definition.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// C++ program to demonstrate working of // inline namespaces #include <iostream> using namespace std; namespace ns1 { inline namespace ns2 { int var = 10; } } int main() { cout << ns1::var; return 0; } |
We can see from above example that members of an inline namespace are treated as if they are members of the enclosing namespace in many situations (listed below). This property is transitive: if a namespace N contains an inline namespace M, which in turn contains an inline namespace O, then the members of O can be used as though they were members of M or N.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// C++ program to demonstrate working of // inline namespaces inside inline namespaces #include <iostream> using namespace std; namespace ns1 { inline namespace ns2 { inline namespace ns3 { int var = 10; } } } int main() { cout << ns1::var; return 0; } |
The inline specifier makes the declarations from the nested namespace appear exactly as if they had been declared in the enclosing namespace. This means it drags out the declaration (“var” in the above example) from a nested namespace to the containing namespace.
Advantages of using inline namespaces:
- Avoid verbose :Consider the above code, if you want to print “var”, you write:
1 |
cout << ns1::ns2::ns3::var; |
This looks good only if namespace’s names are short as in the above example. But by using inline with namespaces there is no need to type the entire namespace as given above or use the “using” directive.
- Support of Library :The inline namespace mechanism is intended to support library evolution by providing a mechanism that supports a form of versioning. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
// file V99.h: inline namespace V99 { void f(int); // does something better than the V98 version void f(double); // new feature // ... } // file V98.h: namespace V98 { void f(int); // does something // ... } // file Mine.h: namespace Mine { #include "V99.h" #include "V98.h" } // We here have a namespace Mine with both the latest release (V99) and the previous one (V98). If you want to be specific, you can: #include "Mine.h" using namespace Mine; // ... V98::f(1); // old version V99::f(1); // new version f(1); // default version //The point is that the inline specifier makes the declarations from the nested namespace appear exactly as if they had been declared in the enclosing namespace. |
Head over and check out all of the modern C++ features available in Windows C++Builder development.
Design. Code. Compile. Deploy.
Start Free Trial Upgrade Today
Free Delphi Community Edition Free C++Builder Community Edition