P
Patrick Stinson
I am trying to create a way to register static members of a **class**, not
an object, for making an object factory. The main thing I want is to be
able to make a call like
class MyClass
{
public:
MyClass *factory();
};
register(MyClass);
and have a method that calls MyClass::factory() to return a MyClass object
on a call like 'MyClass *o = create("MyClass");'.
Is there any C++ construct that would allow this sort of class registration?
I'd be into using macros and even templates (hopefully not).
Here is a longer example...
main.cpp:
------------------------------------------
#include <map>
#include <typeinfo>
typedef std::map<const char *, void (something::*)()> FactoryMap;
FactoryMap *getMap()
{
// I need there to be exactly one instance of registry.
static FactoryMap registry;
return ®istry;
}
int register(something Class)
{
pair<const char *, void (something::*)()> p(typeid(Class).name(),
Class::factory);
getMap()->insert(p);
}
void *create(const char *classname)
{
FactoryMap::iterator it = getMap()->find(classname);
if(it != getMap()->end())
return it->second();
else
return NULL;
}
class A
{
public:
static A *factory(){return new A;}
};
int aDummy = register(A); // THIS IS THE SORT OF CALL I'M AFTER
class B : public A
{
public:
static A *factory(){return new B;}
};
int bDummy = register(B); // AGAIN, THIS IS THE SORT OF CALL I'M AFTER
int main()
{
A *a = *b
}
an object, for making an object factory. The main thing I want is to be
able to make a call like
class MyClass
{
public:
MyClass *factory();
};
register(MyClass);
and have a method that calls MyClass::factory() to return a MyClass object
on a call like 'MyClass *o = create("MyClass");'.
Is there any C++ construct that would allow this sort of class registration?
I'd be into using macros and even templates (hopefully not).
Here is a longer example...
main.cpp:
------------------------------------------
#include <map>
#include <typeinfo>
typedef std::map<const char *, void (something::*)()> FactoryMap;
FactoryMap *getMap()
{
// I need there to be exactly one instance of registry.
static FactoryMap registry;
return ®istry;
}
int register(something Class)
{
pair<const char *, void (something::*)()> p(typeid(Class).name(),
Class::factory);
getMap()->insert(p);
}
void *create(const char *classname)
{
FactoryMap::iterator it = getMap()->find(classname);
if(it != getMap()->end())
return it->second();
else
return NULL;
}
class A
{
public:
static A *factory(){return new A;}
};
int aDummy = register(A); // THIS IS THE SORT OF CALL I'M AFTER
class B : public A
{
public:
static A *factory(){return new B;}
};
int bDummy = register(B); // AGAIN, THIS IS THE SORT OF CALL I'M AFTER
int main()
{
A *a = *b
}