How to process dynamic source code in C++? Is it possible to use something like eval(“foo”)?
I have some functions that need to be called depending on user’s choice:
void function1 ();
void function2 ();
...
void functionN ();
int main (int argv, char * argv [])
{
char * myString = new char [100];
...
myString = "1" //user input
cout << eval("function"+myString)();
}
How is it usually done?
UPD: Based on slacy’s and clinisbut’s answers I think I need to make a function registry. I suppose it should be made as an array of pointers to functions. Here’s the question, how do I declare an array of pointers to functions?
C++ is a compiled language, and thus, there is no equivalent to “eval()”.
For the specific example you mention, you could make a function registry that maps inputs (strings) to outputs (function pointers) and then call the resultant function.
There are several C++ interpreter libraries that are available, although performance will be very poor, they may accomplish what you want. Google search for “C++ interpreter”. I’ve seen results for “Ch“, “CINT” and “clipp”