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

Dipesh KC picture Dipesh KC · Jun 18, 2012 · Viewed 37.4k times · Source

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

Answer

Hauleth picture Hauleth · Jun 18, 2012

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;
}