Friday, November 15, 2013

C++ and dynamic datatype at run-time

Recently I was working on C++ code that had bunch of if-else statements that resembled following. As you can see there is common code however datatype of couple of variables varies based on the condition.
You can see the pattern here! So moved the common code to a function template of the form
So far so good. However in order to invoke the right function I still needed to use if-else block which was an eye-sore
To avoid if-else block, I decided to use a jump-table using map where key would be datatype (string) and value would be function to be invoked.

In addition to UConfigParam type variables, I needed to add support for other variables of the form UStateVar. To achieve this, I simply added more entries to the ProcessFuncMap without changing code for function invocation or piling up if-else code block.

So there you see, using a combination of function templates and a jump table at run time dynamic declaration of variables is achievable.

If there are known design patterns or other techniques that help achieve same in C++ I'd like to hear about them.

No comments: