C++ 17 – Nested Namespaces simplified
We can define namespaces in a nested manner in C++. From C++ 17, this got simplified using “::” notation instead of nesting.
Before C++ 17, the format used to be as below.
namespace A {
namespace B {
namespace C {
// Your code here
}
}
}
From C++ 17 onwards, a simpler and cleaner format is available below.
namespace A {
// Your code here
}
namespace A::B {
// Your code here
}
namespace A::B::C {
// Your code here
}
Before C++ 17, if we wanted to define three nested namespaces, we would have defined them like the below. They will be under nested blocks, as shown in below sample program. The program is available for download at https://github.com/codeversionmaster/cplusplus/blob/cplusplus17/nested_namespaces_bef_cpp17.cpp.
$ cat nested_namespaces_bef_cpp17.cpp
#include <iostream>
using namespace std;
namespace A {
int a = 1;
namespace B {
int b = 2;
namespace C {
int c = 3;
}
}
}
int main() {
cout << "A::a: " << A::a << endl;
cout << "A::B::b: " << A::B::b << endl;
cout << "A::B::C::c: " << A::B::C::c << endl;
return 0;
}
In the above program, each namespaces A, B, and C have variables a, b, and c, respectively.
You can compile and run to see the output like the one below.
$ g++ nested_namespaces_bef_cpp17.cpp -o nested_namespaces_bef_cpp17
$ ./nested_namespaces_bef_cpp17
A::a: 1
A::B::b: 2
A::B::C::c: 3
With the new format supported by C++ 17, the same program is below for the same namespaces as in the previous program. The program is available for download at https://github.com/codeversionmaster/cplusplus/blob/cplusplus17/nested_namespaces_from_cpp17.cpp.
$ cat nested_namespaces_from_cpp17.cpp
#include <iostream>
using namespace std;
namespace A {
int a = 1;
}
namespace A::B {
int b = 2;
}
namespace A::B::C {
int c = 3;
}
int main() {
cout << "A::a: " << A::a << endl;
cout << "A::B::b: " << A::B::b << endl;
cout << "A::B::C::c: " << A::B::C::c << endl;
return 0;
}
You can compile and run to see the output like the one below.
$ g++ nested_namespaces_from_cpp17.cpp -o nested_namespaces_from_cpp17
$ ./nested_namespaces_from_cpp17
A::a: 1
A::B::b: 2
A::B::C::c: 3