I'm new to C++17 and I ran into a problem when I tried to use structure binding to set values to a couple of array cells. But the regular syntax doesn't work here; it gets confused with the array's brackets.
How can I solve it? Is it even possible?
Example:
std::pair<int, int> makePair() {
return { 10, 20 };
}
int main() {
int arr[20];
// error here
auto [arr[0], arr[1]] = makePair();
}
Binds the specified names to subobjects or elements of the initializer. Like a reference, a structured binding is an alias to an existing object. Unlike a reference, a structured binding does not have to be of a reference type.
As expected, an n array must be declared prior its use. A typical declaration for an array in C++ is: type name [elements]; where type is a valid type (such as int, float ...), name is a valid identifier and the elements field (which is always enclosed in square brackets [] ), specifies the size of the array.
A structured binding declaration performs the binding in one of three possible ways, depending on E. Case 1 : if E is an array type, then the names are bound to the array elements. Case 2 : if E is a non-union class type and tuple_size is a complete type, then the “tuple-like” binding protocol is used.
In case of an array, structured binding also works pretty well. The number of identifiers in structured binding should be the same as the number of array elements: You can qualify the underlying anonymous variable with const or volatile. You can use “&” or “&&” to make it an lvalue or an rvalue reference.
Structured binding allows you to initialize multiple variables with individual elements of a structure, tuple, or array. Often, a function will return multiple values packed in a structure.
Each structured binding has a referenced type, defined in the description below. This type is the type returned by decltype when applied to an unparenthesized structured binding. Each identifier in the identifier-list becomes the name of an lvalue that refers to the corresponding element of the array.
It is the wrong tool for the job. Structured bindings always introduce new names; they don't accept arbitrary expressions for lvalues.
But you can do what you want even in C++11. There's std::tie
, for this exact purpose:
std::tie(arr[0], arr[1]) = makePair();
Give it a bunch of lvalues for arguments, and it will produce a tuple of references to them. std::tuple
interacts with std::pair
(considered as two-tuple), and the member-wise assignment modifies the array elements you named.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With