0

What is the correct syntax of structured bindings when the left-hand side is a reference to an array member?

For example, the following program does not compile:

#include <array>

std::array<int, 2> f()
{
    return { 1, 2 };
}

int main()
{
    std::array<int, 4> a;
    a.fill(3);
    auto [ a[1], a[2] ] = f();
}

giving error

main.cpp: In function 'int main()':

main.cpp:12:13: error: expected ']' before '[' token

   12 |     auto [ a[1], a[2] ] = f();

The same goes if the structured binding is written as

auto [ std::get<1>(a), std::get<2>(a) ] = f();
francesco
  • 7,189
  • 7
  • 22
  • 49
  • @bartop Well, transforming the array to a tuple and then using ```std::tie``` as in the linked question works to solve the specific program example. Or, even simpler, one could have f() to return a tuple instead of an array. But my question was explicitly on how to use structured bindings. If this is possible at all. – francesco May 25 '20 at 09:33

1 Answers1

2

structure binding declares new variables,

if you want to reuse existing variable, std::tie is more appropriate.

auto [ a1, a2 ] = f();
std::tie(a[1], a[2]) = std::tie(a1, a2);
Jarod42
  • 203,559
  • 14
  • 181
  • 302