I need to make, for my college homework, an interpreter in C++ for a language based on functions (or commands). The interpreter has got to read an input file, extract the words (strings), generate the commands and execute them. All commands are classes which inherit from a common super-class (Command, for example), which’s got a virtual method called execute. For each word read from the input file, a command is created and stored in a vector<Command>.
So, I’m thinking of using a hashtable, whose keys are the names of the commands (strings) and whose values are some kind of objects which allow me to create an specific class (or give me access to the constructor of an specific class), to easily create the classes for each word instead of using a chain of if-else-if’s.
By now, I’m planning to create a CommandGenerator class with a virtual method called generate which returns a new Command object. The values of my commands hash table will be objects of theCommandGenerator class. So I derive from it many other subclasses for all commands, which return specific new objects derived from Command.
But, does anything like that already exist? Or is there any more elegant way to do that? Is there any kind of object that can be extracted from a class to represent it?
If each command is a subclass of
Command, why don’t you use astd::vector<Command*>and push pointers to instances of each subclass? Then you can iterate over the vector and call your virtualexecutefunction.The closest thing you can get about placing classes in a vector is
boost::fusion::vector. But can’t be filled at runtime, no use on your specific case.Assuming you can use C++11. If you can define commands as just a
executefunction, you can do something like:And then put the command on a vector with:
Then just execute with a loop:
This should print
112to screen. But if you care a lot with speed, do a lot of ifs instead.