I’m doing something that seems like it could be improved, but I don’t have sufficient skill to improve it. Can you help?
Given:
vector<Base*> stuff;
const vector<MetaData>& metaDataContainer = Config.getMetaData();
for(vector<MetaData>::const_iterator i = metaDataContainer.begin(), end = metaDataContainer.end(); i != end; ++i)
{
Base* pCurrent = buildDerivedType(*i);
stuff.push_back(pCurrent);
}
Base* buildDerivedType(MetaData meta)
{
Base* pRetval = NULL;
switch(meta)
{
case MetaData::A:
pRetval = new Alpha();
break;
case MetaData::B:
pRetval = new Beta();
break;
//so on so forth
};
return pRetval;
}
I feel like the switch statement is bad because at compile time all the enum values are known, so theoretically we already know what types need to go into vector stuff. But we do that at runtime.
Short of writing a code generator for this, is there a better way?
Not really. However, you can abstract away much of the boilerplate with a factory type and use boost::ptr_vector or a container of smart pointers to manage the resources in a smart way. (See comments about the choice between smart container vs dumb container of smart pointers.)