c++c++17std-pair

One liner tuple/pair unpack in c++ with reusing same variable multiple times


I have already seen Is there a one-liner to unpack tuple/pair into references? and know how the unpack values from tuple/pairs in a single line like following

auto [validity, table] = isFieldPresentAndSet(r, "is_federated");

here isFieldPresentAndSet returns a tuple.

Now I want to reuse these two variable in multiple successive calls of isFieldPresentAndSet like following

auto [validity, table] = isFieldPresentAndSet(r, "is_federated");
auto [validity, table] = isFieldPresentAndSet(r, "gslb_sp_enabled");

and then check the value for the validity and table. But this gives me compile error because I am redefining the validity and table variable second time. If the change the second line to

[validity, table] = isFieldPresentAndSet(r, "gslb_sp_enabled"); 

or

validity, table = isFieldPresentAndSet(r, "gslb_sp_enabled"); 

It still gives me compile error.

Is there any way to do this??


Solution

  • You can use std::tie. It returns a tuple of references, which makes the assignment possible:

    std::tie(validity, table) = isFieldPresentAndSet(r, "gslb_sp_enabled");