In this chapter, we will cover thefollowing recipes:
- Using structured bindings to unpack bundled return values
- Limiting variable scopes to
if
andswitch
statements - Profiting from the new bracket initializer rules
- Letting the constructor automatically deduce the resulting template class type
- Simplifying compile-time decisions with constexpr-if
- Enabling header-only libraries with inline variables
- Implementing handy helper functions with fold expressions
C++ got a lot of additions in C++11, C++14, and, most recently, C++17. By now, it is a completely different language compared to what it was just a decade ago. The C++ standard does not only standardize the language, as it needs to be understood by the compilers, but also the C++ standard template library (STL).
This book explains how to put the STL to the best use with a broad range of examples. But at first, this chapter will concentrate on the most important new language features. Mastering them will greatly help you write readable, maintainable, and expressive code a lot.
We will see how to access individual members of pairs, tuples, and structures comfortably with structured bindings and how to limit variable scopes with the newif
and switch
variable initialization capabilities. The syntactical ambiguities, which were introduced by C++11 with the new bracket initialization syntax, which looks the same for initializer lists, were fixed bynew bracket initializer rules. The exacttypeof template class instances can now bededucedfrom the actual constructor arguments, and if different specializations of a template class will result in completely different code, this is now easily expressible with constexpr-if. The handling of variadic parameter packs in template functions became much easier in many cases with the newfold expressions. At last, it became more comfortable to define static globally accessible objects in header-only libraries with the new ability to declare inline variables, which was only possible for functions before.
Some of the examples in this chapter might be more interesting for implementers of libraries than for developers who implement applications. While we will have a look at such features for completeness reasons, it is not too critical to understand all the examples of this chapter immediately in order to understand the rest of this book.
C++17 comes with a new feature, which combines syntactic sugar and automatic type deduction: structured bindings. These help to assign values from pairs, tuples, and structs into individual variables. In other programming languages, this is also called unpacking.
Applying a structured binding in order to assign multiple variables from one bundled structure is always one step. Let's first see how it was done before C++17. Then, we can have a look at multiple examples that show how we can do it in C++17:
- Accessing individual values of an
std::pair
: Imagine we have a mathematical function,divide_remainder
, which accepts a dividend and a divisor parameter and returns the fraction of both as well as the remainder. It returns those values using anstd::pair
bundle:
Consider the following way of accessing the individual values of the resulting pair:
Instead of doing it as shown in the preceding code snippet, we can now assign the individual values to individual variables with expressive names, which is much better to read:
- Structured bindings also work with
std::tuple
: Let's take the following example function, which gets us online stock information:
Assigning its result to individual variables looks just like in the example before:
- Structured bindings also work with custom structures: Let's assume a structure like the following:
Now, we can access these members using structured bindings. We can even do that in a loop, assuming we have a whole vector of those:
Structured bindings are always applied with the same pattern:
- The list of variables
var1, var2, ...
must exactly match the number of variables contained by the expression being assigned from. - The
<pair, tuple, struct, or array expression>
must be one of the following:- An
std::pair
. - An
std::tuple
. - A
struct
. All members must be non-static and defined in the same base class. The first declared member is assigned to the first variable, the second member to the second variable, and so on. - An array of fixed size.
- An
- The type can be
auto
,const auto
,const auto&
, and evenauto&&
.
Note
Not only for the sake of performance, always make sure to minimize needless copies by using references when appropriate.
If we write too many or not enough variables between the square brackets, the compiler will error out, telling us about our mistake:
This example obviously tries to stuff a tuple variable with three members into only two variables. The compiler immediately chokes on this and tells us about our mistake:
A lot of fundamental data structures from the STL are immediately accessible using structured bindings without us having to change anything. Consider, for example, a loop that prints all the items of an std::map
:
This particular example works because when we iterate over an std::map
container, we get the std::pair<const key_type, value_type>
nodes on every iteration step. Exactly these nodes are unpacked using the structured bindings feature (key_type
is the species
string and value_type
is the population count size_t
) in order to access them individually in the loop body.
Before C++17, it was possible to achieve a similar effect using std::tie
:
This example shows how to unpack the resulting pair into two variables. The std::tie
is less powerful than structured bindings in the sense that we have to define all the variables we want to bind to before. On the other hand, this example shows a strength of std::tie
that structured bindings do not have: the value std::ignore
acts as a dummy variable. The fraction part of the result is assigned to it, which leads to that value being dropped because we do not need it in that example.
Note
When using structured bindings, we don't have tie
dummy variables, so we have to bind all the values to named variables. Doing so and ignoring some of them is efficient, nevertheless, because the compiler can optimize the unused bindings out easily.
Back in the past, the divide_remainder
function could have been implemented in the following way, using output parameters:
Accessing it would have looked like the following:
A lot of people will still prefer this over returning complex structures like pairs, tuples, and structs, arguing that this way the code would be faster, due to avoided intermediate copies of those values. This is not true any longer for modern compilers, which optimize intermediate copies away.
Note
Apart from the missing language features in C, returning complex structures via return value was considered slow for a long time because the object had to be initialized in the returning function and then copied into the variable that should contain the return value on the caller side. Modern compilers support return value optimization (RVO), which enables for omitting intermediate copies.