C ++ does not have automatic compilation or runtime of its code in the language. Many library frameworks have a reflection of time in the symbols in the library.
So, solution 1: Insert your problems into your own dynamic libraries, and the main program dynamically loads them and looks for the names of the characters they export.
Solution 2: Replace your raw C-style functions with named objects. So you can:
class Problem; void RegisterProblem( std::string name, Problem const* problem ); std::map< std::string, Problem const* >& GetProblems(); class Problem { protected: Problem( std::string name ): RegisterProblem( std::move(name), this ) {} virtual void operator() const = 0; virtual ~Problem() {} }; class Problem1: public Problem { public: Problem1():Problem("Problem1") {} virtual void operator() const { } };
We have some badly written code error, in which there are self-determining problems (which are registered in the static map) and main (), which fulfills any problem indicated in the line.
I think it would be cleaner:
// In RegisterProblem.h: // these two have obvious implementations: std::map< std::string, std::function<void()> >& GetProblems(); bool RegisterProblem( std::string s, std::function<void()> ); // always returns true // In problem1.cpp: void Problem1(); // implement this! bool bProblem1Registered = RegisterProblem( "Problem1", Problem1 ); // In problem2.cpp: void Problem2(); // implement this! bool bProblem2Registered = RegisterProblem( "Problem2", Problem2 ); // etc // in main.cpp: int main(int argc, char** argv) { if (argc == 0) return -1; // and maybe print help auto it = GetProblems().find( argv[1] ); if (it == GetProblems().end()) return -1; // and maybe print help it->second(); // call the problem }
where we eliminate the unnecessary class hierarchy and just maintain the map between the lines and void() functions. The contents of this map apply to every place where functions are written, so there is no central list or if statement.
I would not send anything with such rude code as above, but I hope you understand this idea.
source share