...

/

Use Structured Binding to Return Multiple Values

Use Structured Binding to Return Multiple Values

Learn to use structured binding to return multiple values.

We'll cover the following...

Structured bindingStructured binding is a C++ feature that enables the unpacking of tuple-like objects into individual variables by using a single statement. makes it easy to unpack the values of a structure into separate variables, improving the readability of our code.

With structured binding we can directly assign the member values to variables like this:

things_pair<int,int> { 47, 9 };
auto [this, that] = things_pair;
cout << format("{} {}\n", this, that);

Output:

47 9

How to do it

  • Structured binding works with pair, tuple, array, and struct. Beginning with C++20, this includes bit-fields. This example uses a C-array:

int nums[] { 1, 2, 3, 4, 5 };
auto [ a, b, c, d, e ] = nums;
cout << format("{} {} {} {} {}\n", a, b, c, d, e);
...