Generating a function at runtime has a lot of drawbacks (if it is possible at all) and there is generally no good reason to do it in a language like C++. You should leave that to scripting languages (like Perl or Python), many offer a eval()
function that can interpret a string like script code and execute it.
If you really, really need to do have something like eval()
in a compiled language such as C++, you have a few options:
- Define your own scripting language and write a parser/interpreter for it (lots of work)
- Define a very simple imperative or math language that can be easily parsed and evaluated using well-known design patterns (like Interpreter)
- Use an existing scripting language that can be easily integrated into your code through a library (example: Lua)
- Stuff the strings of code you want to execute at runtime through an external interpreter or compiler and execute them through the operating system or load them into your program using dlopen/LoadLibrary/etc.
(3.) is probably the easiest and best approach. If you want to keep external dependencies to a minimum or if you need direct access to functionality and state inside your main program, I suggest you should go for (2.) Note that you can have callbacks into your own code in that case, so calling native functions from the script is not a problem. See here for a tutorial
If you can opt for a language like Java or C#, there's also the option to use the compiler built into the runtime itself. Have a look here for how to do this in Java