There\'s this one thing in C++ which has been making me feel uncomfortable for quite a long time, because I honestly don\'t know how to do it, even though it sounds simple:<
You can read a very good solution in: http://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus
The best solution is on the "comments and discussions", see the "No need for static Create methods".
From this idea, I've done a factory. Note that I'm using Qt, but you can change QMap and QString for std equivalents.
#ifndef FACTORY_H
#define FACTORY_H
#include
#include
template
class Factory
{
public:
template
void registerType(QString name)
{
static_assert(std::is_base_of::value, "Factory::registerType doesn't accept this type because doesn't derive from base class");
_createFuncs[name] = &createFunc;
}
T* create(QString name) {
typename QMap::const_iterator it = _createFuncs.find(name);
if (it != _createFuncs.end()) {
return it.value()();
}
return nullptr;
}
private:
template
static T* createFunc()
{
return new TDerived();
}
typedef T* (*PCreateFunc)();
QMap _createFuncs;
};
#endif // FACTORY_H
Sample usage:
Factory f;
f.registerType("Descendant1");
f.registerType("Descendant2");
Descendant1* d1 = static_cast(f.create("Descendant1"));
Descendant2* d2 = static_cast(f.create("Descendant2"));
BaseClass *b1 = f.create("Descendant1");
BaseClass *b2 = f.create("Descendant2");