
上QQ阅读APP看书,第一时间看更新
How it works...
Structured bindings are always applied with the same pattern:
auto [var1, var2, ...] = <pair, tuple, struct, or array expression>;
- 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.
- The type can be auto, const auto, const auto&, and even auto&&.
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:
std::tuple<int, float, long> tup {1, 2.0, 3};
auto [a, b] = tup; // Does not work
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:
error: type 'std::tuple<int, float, long>' decomposes into 3 elements, but only 2 names were provided
auto [a, b] = tup;