1

Possible Duplicate:
Is there a way to instantiate objects from a string holding their class name?

I'm working on a problem in some C++ code that has a base class InputFile, and a number of derived classes: TxtInputFile, ASCInputFile, etc, where each derived class is a specific input type.

What I'd like to be able to do is to take a variable off the command line, and then generate the correct derived class object to deal with the indicated file type (e.g. user indicated TXT off the command line, so, I generate a TXTInputFile object and return under the InputFile label for use in the rest of the program).

I could do this with a string of IF / 'ELSE` statements, comparing the user-input with a bunch of predetermined file codes, but I'd like to be able to add support for new file types in the future without editing a string of if statements and adding new file codes, etc.

Is there any way to get access to some compiler generated table of all derived classes to a base class at runtime?

Or perhaps some sort of polymorphic constructor that is dynamically bound based on what the passed parameter is equal to?

(e.g. InputFile(string)... TXTInputFile(string temp = "TXT"), ASCInputFile(string temp = ASC")... I realize that's the format for default values to parameters, just trying to suggest where I was going with that train of thought.)

Thanks in advance.

Community
  • 1
  • 1
LiamK
  • 795
  • 6
  • 16

2 Answers2

5

You can make a mapping (perhaps with std::map) from strings to factory functions.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

Don't roll your own parser if the parsing is at all complex. There are lots of options, ranging from the old standby lex/yacc (or flex/bison) to Boost::Spirit to ANTLR. Lex/yacc is a LALR parser and it generates code. The generated code is a bit hard to follow and debug. Boost::Spirit is much more in line with modern programming concepts, as is ANTLR. The basic idea is that you specify the grammar and how that grammar is to be processed.

David Hammen
  • 32,454
  • 9
  • 60
  • 108
  • Hadn't even considered a parser, but just briefly glancing over ANTLR, it looks like that will get the job done nicely. Bit more overhead than I'd like, but I'm not sure there's a way around that. – LiamK Oct 01 '12 at 11:22