As described in This Answer, you can determine a derived object from a string, as long as you know the base type. I wanted to make the code more flexible by making the BaseFactory a template, which results in the following compilable code.
#include <iostream>
#include <string>
#include <map>
///Reflect and Register
#define MyType(BASE, TYPE) \
static Registerer<BASE, TYPE> reg
#define Register(BASE, TYPE) \
Registerer<BASE, TYPE> TYPE::reg(#TYPE)
template<class B>
class Factory
{
public:
static B* from(const std::string& name)
{
return mapping[name];//should check if its a member
}
static void add(const std::string& name, B* instance)
{
mapping[name] = instance;
}
static std::map<std::string, B*> mapping;
};
template<class B>
std::map<std::string, B*> Factory<B>::mapping = std::map<std::string, B*>();
template<class B, class D>
class Registerer
{
public:
Registerer(const std::string& name)
{
Factory<Base>::add(name, new D);//actually add
}
};
///Deduce and Register
///Class examples implementing Registration
class Base
{
public:
Base()
{
name = "Base Class";
}
const std::string& getName()
{
return name;
}
protected:
std::string name;
};
class Derived1 : public Base
{
public:
Derived1()
{
name = "I am type 1.\n";
}
MyType(Base, Derived1);
};
Register(Base, Derived1);
class Derived2 : public Base
{
public:
Derived2()
{
name = "I am type 2.\n";
}
MyType(Base, Derived2);
};
Register(Base, Derived2);
///Class examples implementing Registration
int main()
{
std::string typeString1 = "Derived1";
std::string typeString2 = "Derived2";
std::cout << Factory<Base>::from(typeString1)->getName();
std::cout << Factory<Base>::from(typeString2)->getName();
return 0;
}
However, this code crashes, apparently because Factory::mapping does not get instantiated in time for when Registerer calls add. As described in This Answer, there is a solution, which is to add the line
template class Factory<Base>;
which does not fix the problem in Visual Studio, which is what I'm using. The other possibility is to explicitly make a new class, but the whole point was to use a template in the first place. So I came up with this:
template<class B>
class Factory
{
public:
static B* from(const std::string& name, B* instance = NULL)
{
static std::map<std::string, B*> mapping;
if(instance != NULL)
{
mapping[name] = instance;
return NULL;
}
else//should check if name is in map first
return mapping[name];
}
};
Which works since the mapping variable is initialized the first time the function is called. The unfortunate part is the if check.
I'm trying to find a solutions that:
-
Does not use a single function in Factory to simulate two.
-
A way to register a class with a single line instead of two.
-
The ability to force a child class of Base to register itself, to prevent a user accidentally not registering it.
Aucun commentaire:
Enregistrer un commentaire