- Hands-On System Programming with C++
- Dr. Rian Quinn
- 146字
- 2021-07-02 14:42:39
Namespaces
A welcome change to C++17 is the addition of nested namespaces. Prior to C++17, nested namespaces had to be defined on different lines, as follows:
#include <iostream>
namespace X
{
namespace Y
{
namespace Z
{
auto msg = "Hello World\n";
}
}
}
int main(void)
{
std::cout << X::Y::Z::msg;
}
// > g++ scratchpad.cpp; ./a.out
// Hello World
In the preceding example, we define a message that is output to stdout in a nested namespace. The problem with this syntax is obvious—it takes up a lot of space. In C++17, this limitation was removed by giving us the ability to declare nested namespaces on the same line, as follows:
#include <iostream>
namespace X::Y::Z
{
auto msg = "Hello World\n";
}
int main(void)
{
std::cout << X::Y::Z::msg;
}
// > g++ scratchpad.cpp; ./a.out
// Hello World
In the preceding example, we are able to define a nested namespace without the need for separate lines.