it need a way to call function whose name is stored in a string similar to eval. Can you help?
In short, writing an implementation for eval in C is possible, but a huge amount of work that requires a lot of expertise and knowledge in several fields of computer science.
Nope, your best bet is the command pattern. There are some C++ interpreters: stackoverflow.com/questions/69539/… -1 This is a terrible idea and I cannot in good conscience encourage it. If you get in the habit of solving problems with eval , you are getting in a very, very bad habit.
An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().
C++ doesn't have reflection so you must hack it, i. e.:
#include <iostream> #include <map> #include <string> #include <functional> void foo() { std::cout << "foo()"; } void boo() { std::cout << "boo()"; } void too() { std::cout << "too()"; } void goo() { std::cout << "goo()"; } int main() { std::map<std::string, std::function<void()>> functions; functions["foo"] = foo; functions["boo"] = boo; functions["too"] = too; functions["goo"] = goo; std::string func; std::cin >> func; if (functions.find(func) != functions.end()) { functions[func](); } return 0; }
There are at least 2 alternatives:
GetProcAddress
to get a callback by name, and dlopen
+ dlsym
on *nix.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With