I'm always been coding in C++11 and I'm trying to understand how auto works in newer versions. In particular I have a two functions (f1 and f2 in the example) that work on a given struct. Both functions are almost the same but they change on what member they are operating, sometimes the operation is the inverse of one value, etc... (this example is an over simplification of the real program).
I want to avoid using conditionals and overloading functions to achieve thie behaviour. Do you know of a cleaner, or more idiomatic, way to do this? Are there any problems in this code that I'm missing out?
typedef struct thing_t {
double A;
double B;
} THING;
double get_A(const THING &t) {
return t.A;
}
double get_B(const THING &t) {
return t.B;
}
double convert(const THING &t, auto first, auto then) {
return first(t) / then(t);
}
double f1(const THING &t) {
return convert(t, get_A, get_B);
}
double f2(const THING &t) {
return convert(t, get_B, get_A);
}
int main() {
THING t = {1.0, 2.0};
std::cout << f1(t) << std::endl;
std::cout << f2(t) << std::endl;
return 0;
}
Thank you very much for taking the time to review my question.
Aucun commentaire:
Enregistrer un commentaire