This is the second part of the series “6 Useful New Features in C++17”, the first part can be found here.
One thing that has been bugging me when trying to write nice looking code is iterating through maps. Most often it is when acting on information read from a JSON or XML file, where if a key is found then something should be done with the value.
For example, an application has a set of settings with default values, but a user can set their own values for these settings. However, the file specifying these user specific values only needs to contain those settings that deviate from the default values. A code snippet doing that could look like:
With Structured Binding supported by C++17 this can be rewritten in a prettier and more readable way:
One other example where structured binding helps you clean up your code would be when one needs to handle tuples.
Doesn’t look very intuitive even in this very simple example. What we could do before C++17 is make use of std::tiewhich unpacks the tuple into independent variables.
Well, I like this better. However, it is a bit cluttered because we need to declare the variables which is used in std::tie. Fortunately, structured binding lets us get rid of that as well:
Please note that structured binding can be used with other types than tuples!
These features are all fully supported by GCC, MSVC, and clang. Below follows a table showing which version enables support for each feature respectively.
For more a detailed matrix with more compilers and all features of C++17 listed, follow this link.
READ PART 3 “6 Useful New Features in C++17” HERE.
// Patrik Ingmarsson