I have a couple functions that return not just one variable, but a collection of variables. For example, a root finder might return the found root, iterations needed, and whether the root-finding process was indeed successful.
struct ReturnData {
const double root;
const size_t iterations;
const bool success;
};
template <class FuncType>
ReturnData findRoot(const FuncType& f, const double& guess) {
double root = guess;
size_t iterations = 0;
while(true) { /*... find root ...*/ }
return { root, iterations, true };
}
Now this works if I am only returning a small number of variables. But maybe I want to include a possible error message like const std::string errorMessage in my ReturnData, as well as other reference meta data. So when scaling this to, say, more than 10 parameters, it starts to be very easy to make mistakes in using the initializer list to return the data. Maybe I also deleted a parameter, or I re-ordered them, etc. which in turn requires me to carefully apply the same changes to the initializer list at the end of function findRoot.
What is a good systematic approach to return data from a function like this? My criteria are:
- Clear code that's straight-forward to understand/maintain by other people.
- Somewhat efficient code, meaning that I don't want to construct overly elaborate return structures (since this root-finder might be called many many times, and in the majority of cases people will only care about variable
root).