Are there techniques/libraries that allow the flexibility of having a class hierarchy (that has virtual
functions) yet, once the objects types have been determined at runtime, allows devirtualization of the function calls?
For a simple example, suppose I have a program that reads shape types (circle, rectangle, triangle, etc.) from some configuration file to construct a some data structure of said shapes (e.g., vector<shape*>
):
class shape {
public:
virtual void draw() const = 0;
// ...
};
class circle : public shape {
public:
void draw() const;
// ...
};
// ...
vector<shape*> shapes;
Obviously, if I want to draw all the shapes, I can do:
for ( auto&& s : shapes )
s->draw();
Every time such an iteration over shapes
is done, a virtual
function call is made to call draw()
for every shape.
But suppose once shapes
is created, it's never going to change again for the lifetime of the program; and further suppose that draw()
is going to be called many times. It would be nice if, once the actual shapes are known, there were a way to "devirtualize" the calls to draw()
at runtime.
I know about optimization techniques to devirtualize virtual
function calls at compile time, but I am not asking about that.
I'd be very surprised if there were a clever hack to do this in C++ directly since one way of doing this would be to modify the in-memory machine code at runtime. But is there some C++ library out there that enables such a thing?
I imagine something like this might be possible via LLVM since that allows generation of machine code at runtime. Has anybody used LLVM for this? Perhaps a framework layered on top of LLVM?
NOTE: the solution has to be cross platform, i.e., at least using gcc/clang and VC++.