Language feature: Structured binding
Syntax
1 2 |
auto [i, s, d] = std::make_tuple(1, "abc", 4.5); auto& [i, s, d] = someStruct; |
Tuples and data fetching
Tuples are suggested for returning multiple values from a function. They are in a strong relation with std::tie, which is used for retrieving the values.
The only problem is that we have to have all those variables previously declared.
1 2 3 4 5 6 7 |
auto myTuple = std::make_tuple(1, "abc", 4.5); int i; std::string s; double d; std::tie(i,s,d) = myTuple; |
But what if we wanted to get the reference to those values instead? We cannot do that easily either. The following code will not compile:
1 2 3 4 5 6 7 |
auto myTuple = std::make_tuple(1, "abc", 4.5); int& i; std::string& s; double& d; std::tie(i,s,d) = myTuple; |
In order to do so, we had to use std::get instead.
1 2 3 4 5 |
auto myTuple = std::make_tuple(1, "abc", 4.5); int& i = std::get<0>(myTuple); std::string& s = std::get<1>(myTuple); double& d = std::get<2>(myTuple); |
Structured bindings
Structured Bindings give us the ability to declare multiple variables initialized from a tuple or struct.
Using them, the code looks so much clearer and shorter, and we can either copy the data or access them by reference.
1 2 3 |
auto myTuple = std::make_tuple(1, "abc", 4.5); auto [a, b, c] = myTuple; auto& [i, s, d] = myTuple; |
Other than that, they can also be used with structs in the same way:
1 2 3 4 5 6 7 8 |
struct Foo { int i; std::string s; double d; }; Foo myStruct {1, "abc", 4.5); auto& [i,s,d] = myStruct; |