In my .NET project, I have some code that creates new objects according to an xml. The Activator is the heart of what makes this possible. Is there a similar thing I can do in c++? I've found some IOC/DI frameworks, but I really don't need much functionality. The alternative is of course to simply write a switch, but that would need to be modified (along with the XML) each time I come up with a new type.
The coolest C++ implementation of a "superfactory" is one by my good friend Francis and you can find the article here on CodeProject.
I believe he wrote this factory with exactly this need in mind. It also powers his (de)serialization framework Daabli that reads plaintext C-style (and with some work - JSON, XML) files and recreates object graphs.
Hope this helps!
if you don't want a switch you roll your factory along these lines
#include <map>
#include <string>
class IHasCreate
{
};
typedef IHasCreate* (*CreateFunc)();
std::map<std::string,CreateFunc> factorymap;
class foo : IHasCreate
{
public:
static IHasCreate* CreateFoo()
{
return new foo();
}
};
class bar: IHasCreate
{
public:
static IHasCreate* CreateBar()
{
return new bar();
}
};
IHasCreate* FactoryCreate( const std::string & name )
{
return factorymap[name]();
}
int main()
{
factorymap["foo"] = &foo::CreateFoo;
factorymap["bar"] = &bar::CreateBar;
IHasCreate *fooboject = FactoryCreate("foo");
IHasCreate *barboject = FactoryCreate("bar");
return 0;
}
The adding of stuff to the factorymap can be done by using some kind of macro magic that some people may find more appealing.
#include <map>
#include <string>
class IHasCreate
{
};
typedef IHasCreate* (*CreateFunc)();
std::map<std::string,CreateFunc> factorymap;
bool RegisterType( const std::string& type , CreateFunc func )
{
factorymap[type] = func;
return true;
}
IHasCreate* FactoryCreate( const std::string & name )
{
return factorymap[name]();
}
#define REGISTER(type) \
IHasCreate* type##createfunc() { return new type(); } \
bool type##temp = RegisterType( #type , &type##createfunc);
class foo : public IHasCreate
{
};
REGISTER(foo);
class bar: public IHasCreate
{
};
REGISTER(bar);
int main()
{
IHasCreate *fooboject = FactoryCreate("foo");
IHasCreate *barboject = FactoryCreate("bar");
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With