Ok, so it’s been a while since I wrote anything big in c++ and I’ve grown used to some of the niceties of more modern languages. This is one that’s been nagging at me and I’m sure there’s an answer out there. Is there any way to call a function specified as a string by a user at run-time? Without having to resort to some sort of massive switch/if block?
The situation I’m in boils down to this: I’ve got a whole whack-load of math-related problems I’ve solved in C++ and specified as “Problem1.cpp/Problem1.h”, “Problem2.cpp/Problem2.h”, etc. Each problem has a function called problemX() (where X is the number of the problem) that kicks off the solution.
At the start of the program I’d like to ask the user “Which problem would you like to solve?” and they’d specify a number. I’d then like to call the appropriate problemX() function without having to resort a massive hard coded switch statement (or an if statement, or an indexed array of function pointers, etc).
I’m sure this has got to be possible, but I just can’t remember how to go about it. Any ideas?
C++ has no automatic compile or run time reflection of its code in the language. Many library frameworks do have run time reflection of the symbols in a library.
So solution 1:
Stick your problems into their own dynamic libraries, and have the main program dynamically load them and look up the symbol names they export.
Solution 2:
Replace your raw C-style functions with named objects. So you might have:
Above we have some horribly written spew of code that has self-registering Problems (who register in a static map), and a main() that executes whatever problem the string specifies.
A way I think would be cleaner is:
where we do away with the needless class hierarchy and just maintain a map between string and
void()functions. The maintenance of this map is distributed to each place where the functions are written, so there is no central list or if statement.I wouldn’t ship anything with code as crude as the above, but I hope you get the idea.