I have some code that looks like this (EDIT: my condition depends on the first computation):
int res2;
int res1 = fancy_computation(blah, &res2);
if (condition(res1))
res1 = fancy_computation_but_slightly_different(blah2, &res2);
do stuff with res1 and res2;
Naturally, using pointers to fake a pair of retvals is no bueno, and I'd love to replace it with structured bindings:
auto [res1, res2] = fancy_computation(blah);
if (condition(res1))
auto [res1, res2] = fancy_computation_but_slightly_different(blah2);
do stuff with res1 and res2;
Naturally this gives me warnings about the second binding shadowing the first variables, which honestly I don't care about, but the project rules say warnings are errors. Also, the maintainers have previously rejected using the std::tie
hack. Declaring new variables res1b
res2b
wouldn't work either, because for the purposes of the following block I'd have to re-assign res1 = res1b
res2 = res2b
, which would very much defeat the purpose of "making it more readable than pointer-retvals".
Is there any hope to fix this, and be rid of the res2
pointer?
I've reviewed some other SO questions, none directly answer this question (altho many say "no luck doing that usecase with structured bindings", which I kind of expect here...)
You can use lambda:
auto [res1, res2] = [&] {
auto [res1, res2] = fancy_computation(blah);
if (condition(res1))
return fancy_computation_but_slightly_different(blah2);
return std::pair{res1, res2};
}();
// do stuff with res1 and res2