C++17 enables writing simple, clearer, and more expressive code. Some of the features introduced in C++17 are:

  • Nested Namespaces
  • Variable declaration in if and switch
  • if constexpr statement
  • Structured bindings
  • Fold Expressions
  • Direct list initialization of enums

Nested Namespaces

Namespaces are a very convenient tool to organize and to structure the code base, putting together components like classes and functions that logically belong to the same group.

Let’s consider a hypothetical code base of a video game engine. Here, defined a namespace for the whole game engine, so all the classes and the functions implemented in this Game Engine will be declared under this common namespace. To do more clear definitions you can define another namespace under the global namespace lets say Graphics which is a sub-namespace, now put all classes that perform graphics operations under that namespace and so on.

  • Before C++17:
  • Below is the syntax used for nested namespace:
// Below is the syntax for using 
// the nested namespace 

namespace Game { 

    namespace Graphics { 

        namespace Physics { 

           class 2D { 
              .......... 
           }; 
        } 
    } 
} 
  • When C++17:
  • Before C++17 you have to use this verbose syntax for declaring classes in nested namespaces, but C++17 has introduced a new feature that makes it possible to open nested namespaces without this hectic syntax that require repeated namespace keyword and keeping track of opening and closing braces. In C++17 there a simple and concise syntax using double colons to introduce nested namespaces. The syntax is as follows:
// Below is the syntax to use the 
// nested namespace in one line 

namespace Game::Graphics::Physics { 

    class 2D { 
       .......... 
    }; 
} 
  • This makes the code less error-prone as there is no need to pay attention to several levels of braces.

#c++ #cplusplus #programming-c #c++17

Features of C++17 with Examples
2.50 GEEK