c++ - Calling a function using a string containing the function's name -


i have class defined

class modify_field  {     public:         std::string modify(std::string str)         {             return str;         }  }; 

is there way store function name inside string in main function , call it. tried it's not working.

int main() { modify_field  mf; std::string str,str1,str2; str = fetch_function_name(); //fetch_function_name() returns string modify str2 = "check"; cout << str; //prints modify str1 = str + "(" +str2 + ")"; mf.str1();  } 

i know wrong. want know if there way call function name using variable.

this not directly possible in c++. c++ compiled language, names of functions , variables not present in executable file - there no way code associate string name of function.

you can similar effect using function pointers, in case trying use member function well, complicates matters little bit.

i make little example, wanted answer in before spend 10 minutes write code.

edit: here's code show mean:

#include <algorithm> #include <string> #include <iostream> #include <functional>  class modify_field  { public:     std::string modify(std::string str)         {             return str;         }      std::string reverse(std::string str)         {             std::reverse(str.begin(), str.end());             return str;         } };   typedef std::function<std::string(modify_field&, std::string)> funcptr;   funcptr fetch_function(std::string select) {     if (select == "forward")         return &modify_field::modify;     if (select == "reverse")         return &modify_field::reverse;     return 0; }    int main() {     modify_field mf;      std::string example = "cat";      funcptr fptr = fetch_function("forward");     std::cout << "normal: " << fptr(mf, example) << std::endl;      fptr = fetch_function("reverse");     std::cout << "reverse: " << fptr(mf, example) << std::endl; } 

of course, if want store functions in map<std::string, funcptr>, entirely possible.


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -