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

1

15

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??

Kentiga answered 13/10, 2022 at 14:4 Comment(8)
add {} around the block to make the vars local to that scope?Thirteenth
Nope. I have to put both tuple unpacking into separate scope. But the checking after calling the function would happen outside.Kentiga
std::tie(validity, table) = isFieldPresentAndSet(r, "gslb_sp_enabled"); ?Sinatra
Unclear to me because that means you unpack multiple times and check once???Thirteenth
@Thirteenth yes that's what I am doingKentiga
structured_binding is C++17 though, tags fixed.Sinatra
@Sinatra yes I could use tie but I was looking for more cleaner solution. Thanks though!Kentiga
If you check once, you get only the result of last unpacking... really? :-)Thirteenth
A
17

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");
Amaro answered 13/10, 2022 at 14:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.