Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c++ > #83007
| From | Paavo Helde <eesnimi@osa.pri.ee> |
|---|---|
| Newsgroups | comp.lang.c++ |
| Subject | Structured binding: referencing an existing variable |
| Date | 2022-02-16 08:46 +0200 |
| Organization | A noiseless patient Spider |
| Message-ID | <sui6ki$p37$1@dont-email.me> (permalink) |
I was cleaning up some code and getting rid of an obscure in-out
reference parameter by replacing it by a tuple return. E.g. with a
simplified example, instead of former
A foo(int& pos_in_out);
we now have
std::pair<A, int> foo(int pos_in);
where the updated pos is returned explicitly.
Now how do I capture these results when calling it? In the old call it was:
int pos = 0;
while(pos < N) {
A a = foo(pos);
// ...
}
How should I replace it? The thing is A does not have a default ctor and
should be created afresh each time when foo is called, while pos should
be updated instead.
std::tie(a, pos) = foo(pos); // Does not work for A as it cannot be
pre-constructed.
An alternative is to use C++17 structured binding:
auto [a, pos] = foo(pos); // Does not work for pos as it creates a new
variable, instead of updating the old one.
In short, I would want to use structured binding for A and effectively
std::tie() for the other member. Is that somehow possible?
For now I resorted to:
auto [a, newPos] = foo(pos);
pos = newPos;
but this introduces an unneeded extra variable and does not look like so
great improvement over the old code.
Back to comp.lang.c++ | Previous | Next — Next in thread | Find similar | Unroll thread
Structured binding: referencing an existing variable Paavo Helde <eesnimi@osa.pri.ee> - 2022-02-16 08:46 +0200
Re: Structured binding: referencing an existing variable Manfred <noname@add.invalid> - 2022-02-16 21:43 +0100
Re: Structured binding: referencing an existing variable Vir Campestris <vir.campestris@invalid.invalid> - 2022-02-16 22:00 +0000
Re: Structured binding: referencing an existing variable Paavo Helde <eesnimi@osa.pri.ee> - 2022-02-17 16:00 +0200
csiph-web