I have a function that forwards some large variables via const reference like this:
void processMore(const std::vector<int> &a, const std::vector<int> &b);
void process(const std::vector<int> &a,
const std::vector<int> &b) {
processMore(a, b);
}
But I have added an optimisation that modifies them:
std::pair<std::vector<int>, std::vector<int>>
optimise(const std::vector<int> &a, const std::vector<int> &b);
I can do it unconditionally like this:
void process(const std::vector<int> &a,
const std::vector<int> &b) {
auto opt = optimise(a, b);
processMore(opt.first, opt.second);
}
But I want to make it optional. My solution is this:
void process(const std::vector<int> &a,
const std::vector<int> &b,
bool doOptimisation) {
auto opt =
[&]() -> std::pair<const std::vector<int>&,
const std::vector<int>&> {
if (doOptimisation) {
auto o = optimise(a, b);
return std::make_pair(o.first, o.second);
}
return std::make_pair(a, b);
}();
processMore(opt.first, opt.second);
}
This seems a bit convoluted. Is there a better way? I want to avoid unnecessary copying.
o!return optimise(a, b);?optimise()returns a pair of values, and I need a pair of references.