I have a function as follows:
auto foo(int i) {
struct s {
int i;
std::string name;
};
return s{i 10, "hello there"};
}
And it works fine with structured bindings:
auto [i, name] = foo(10);
Is there a way to reuse the variables? i.e.
// Later in the code.
[i, name] = foo(20);
It doesn't work with std::tie
because I'm not returning a tuple. I prefer a struct as it feels cleaner to me than a tuple. But if there is no other alternative, I'm open to switching to a tuple.
CodePudding user response:
Since the hidden variable introduced by a structured binding is unnamed, there's no easy way to refer to it to a assign a new value.
You could do
auto x = foo(10);
const auto &[i, name] = x;
Then assign to x
to change the meaning of i
and name
.