#How to conditionally reference variables using structured bindings?

5 messages · Page 1 of 1 (latest)

warm sparrow
#

In the following code in function deliver_image I try to conditionally reference either the passed parameters or some new stack variables. It doesn't compile like this, how can I work around this? The idea is that the function parameters can't be altered, so it needs to make a copy, but only if a certain condition (int c == 4) is true.

Godbolt link: https://godbolt.org/z/P7GssedEx

#include <utility>
#include <iostream>
#include <string>
#include <tuple>

using MATRIX = std::string;
using ColorMap = std::string;

volatile int c = 4;

auto shift_vals(const MATRIX& map, const ColorMap& cm) -> std::pair<MATRIX, ColorMap>{
MATRIX new_map;
ColorMap new_cm;
return {new_map, new_cm};
}

auto deliver_image(MATRIX& mapgrid, ColorMap colormap) {

MATRIX new_map;
ColorMap new_cm;
auto& [map, cm] = [&](){
    if (c == 4) {
        std::tie(new_map, new_cm) = shift_vals(mapgrid, colormap);
        return std::pair<MATRIX&, ColorMap&>(new_map, new_cm);
    } else {
        return std::pair<MATRIX&, ColorMap&>(mapgrid, colormap);
    }
}();

}

int main() {

MATRIX mapgrid;
ColorMap cm;
deliver_image(mapgrid, cm);

}

royal chasmBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

winged pewter
#

Remove the & from auto &[map, cm].

#

The & refers to the pair not to the MATRIX and ColorMap.

warm sparrow