Regarding FAQ 36.8: populating the map automatically

T

trbeals

I'm trying to unserialize objects that are part of an inheritance
hierarchy. The advice in 36.8 of the FAQ seems perfect for what I'm
doing, except it leaves one critical question unanswered: how do I
populate the map that takes derived class names and gives me the
appropriate derived class constructor (or, alternatively, a
representative object of the appropriate derived class)?

Of course, I can always populate the map manually in main(), or
something equally ugly, but that requires that main() know about each
of the derived classes, and that main() be modified each time a new
derived class is added to my codebase (which happens rather
frequently). I'd rather have each derived class somehow take care of
adding an appropriate entry for itself to the map, but I'm not sure how
to do this.

One idea I had was to have in each DerivedClass.cpp a global variable
of that class type, initialized using a special constructor that adds
the appropriate entry to the map. This seems ugly, but is it my best
option?

Something like this:

// DerivedClass.cpp
#include "DerivedClass.h"

DerivedClass Foo("DerivedClass");

DerivedClass::DerivedClass(string s) {
BaseClass::addToMap(s, this);
// adds an entry to the map with the string s
// as the key for the map, and this as a representative object
// of the class DerivedClass
}

DerivedClass * DerivedClass::create(std::istream& someStream) {
// etc
}

Assuming I use the Construct on First Use idiom for the map, and call
theMap["className"]->create() when I want to unserialize an object of
type "className", will this work? Is it advised, or is there a Better
Way?
 
I

Ian

I'm trying to unserialize objects that are part of an inheritance
hierarchy. The advice in 36.8 of the FAQ seems perfect for what I'm
doing, except it leaves one critical question unanswered: how do I
populate the map that takes derived class names and gives me the
appropriate derived class constructor (or, alternatively, a
representative object of the appropriate derived class)?
Use a small embedded class that adds the surrounding class to the map
and have a static instance of it as a member of the surrounding class.

class X
{
static std::string name();

struct Mapper
{
Mapper()
{
<someMap>[X::name()] = new X();
}
};
static Mapper mapper;
};

Ian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top