Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there C/C++ equivalent of eval("function(arg1, arg2)")?

Tags:

c++

eval

it need a way to call function whose name is stored in a string similar to eval. Can you help?

like image 264
Dipesh KC Avatar asked Jun 18 '12 07:06

Dipesh KC


People also ask

Is there an eval function in C?

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.

Does C++ have an eval function?

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.

How do you use eval instead of function?

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().


2 Answers

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; } 
like image 135
Hauleth Avatar answered Sep 21 '22 17:09

Hauleth


There are at least 2 alternatives:

  • The command pattern.
  • On windows, you can use GetProcAddress to get a callback by name, and dlopen + dlsym on *nix.
like image 32
Luchian Grigore Avatar answered Sep 19 '22 17:09

Luchian Grigore