Use Structured Binding to Return Multiple Values
Explore the use of structured binding in C++20 to return and unpack multiple values from tuple-like objects, pairs, arrays, and structs. Learn how this feature enhances code readability and maintains type safety while allowing manipulation through references.
We'll cover the following...
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, andstruct. 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);