vendredi 9 janvier 2015

Choose and evaluate a function from a list in C++11

Using C++, I need to choose a function from a list and then evaluate that function with some inputs. I know just enough to be dangerous, I've solved my problem through some magic, but I have questions regarding my solution. Here is a minimal working example:



double foo(double x) {return x+2;}
double bar(double x) {return x*7;}
double baz(double x) {return x-1;}

int main() {

double x = 3;
auto func_list = {foo,bar,baz};

// This is chosen from an external source,
// setting to a fixed value for the example
int random_choice = 1;

double y = (*(func_list.begin()+random_choice))(x);

return 0;
}


Question: Is this the right way to chose a function from a list and evaluate it? auto here was a double-edged sword, it created something, but I don't know what type it is.


Aucun commentaire:

Enregistrer un commentaire