I am loading different types of derived classes from a file, which are of the form:
- 4-byte class ID header
- n-byte serialized data
Each of the classes are inherited from a same base class, but I have some trouble creating them elegantly. This is my current code (here Foo and Bar are inherited from the same type):
// read class ID
uint32_t id = ReadHeader(myFile);
// create correct class
switch (id)
{
case ID_CLASS_FOO: myClass = new Foo(myFile); break;
case ID_CLASS_BAR: myClass = new Bar(myFile); break;
/* ... */
}
But I find this rather ugly, tedious and prone to error, since for every extra class I add, I need one extra define/enum member, and one additional line in the switch.
What I am looking for is something where I would declare a compile-time "type array" like such:
ClassTypes = {Foo, Bar, ...};
And then, when reading the file, just go:
myClass = new ClassTypes[id](myFile);
Is there some way to do this in C++?