In C ++, this is not possible. C ++ is a compiled language, so the names of functions and variables are not present in the executable file - so the code cannot associate your string with the name of the function.
You can get a similar effect using function pointers, but in your case you are also trying to use a member function, which complicates things a bit.
I will give a small example, but I want to get an answer before spending 10 minutes writing code.
Edit: here is some code to show what I 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 you want to save functions in map<std::string, funcptr> , this is entirely possible.
source share