How can I use structured bindings to set an array's values?

Viewed 118

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();
}
1 Answers

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.

Related