c++ - Create class instance based on a string input -


background:

in game engine have generic 'script parser' used create game entities parsing script file. in code have myentity* entity = myscriptparer::parse("filename.scr");

any class scriptable inherits generic base class. internally in game engine there specific classes use - particles, fonts etc , works nicely in parser - see extract below

std::string line; std::getline(ifs, line);  if (line == "[font]") {     cfont* f = new cfont();     f->readobject(ifs); } else if (line == "[particle]") {     cparticle* p = new cparticle();     p->readobject(ifs); } ... 

my problem comes how handle user defined classes i.e classes in games use game engine. base class has abstract method readobject inherits must implement method.

the issue how parser know new class? e.g have cvehicle class parser need know recognise "[vehicle]" , able create new cvehicle

is there way store class type or in array/map maybe have function register list of class types strings provide lookup creating new instances?

bit of long shot , may not possible if has other suggestions on how approach parsing welcomed

you can store class type in array/map via std::type_info

however, cannot create type this, require more rtti available in c++. (like reflection in .net).

however, store function pointer class factory in such map. i.e.

typedef cbaseclass* (*pfncreateclass)();  std::map<std::string, pfncreateclass> mapcreate;  // registering // cmycustomclass::getclass() static method creates cmycustomclass mapcreate.insert(std::pair<std::string, pfncreateclass>("[custom_class]", cmycustomclass::getclass));  // class std::map<std::string, pfncreateclass>::const_iterator = mapcreate.find(line); if(mapcreate.end() != it) {     cbaseclass *p = it->second();     p->readobject(ifs); } 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -