Search code examples
c++metaprogramming

Does C++ have any runtime metaprogramming functionality?


By "runtime metaprogramming" I mean changing the actual code at runtime.

For example, take this code:

while (true) {
   if (flag) {
      //do stuff
   }
   //do other stuff
}

Let's say something happens so that flag will always be false/true, so there is no need to keep checking its value. It would be nice to just "get rid" of the if statement. Obviously there might just be better design in the code before execution to handle this, but this is just an example.


Solution

  • C++ does not have facilities for modifying code at runtime like that. This is because C++ code is compiled to machine code, and modifying machine code is very difficult, insecure, and non-portable. If you're interested, see the Wikipedia article on Self-modifying code.

    In theory, if you really needed to, you could hoist the test for flag further back, by writing three sets of functions (one where flag is known to be always true, one where it's always false, and one where it could be either) and switch between those sets of functions at an earlier time. However, the code complexity and performance impact of maintaining three separate copies of the functions will not be worth the microscopic speedup from removing one easily-predicted branch.

    If you're concerned about the performance of your application, you will find better opportunities for optimization elsewhere.