I'm gonna show here is more like idea rather than fully working solution. Although it works on my side, here I had to cut down the code to make it clearer and to not reveal any commercial parts of course.
My major goal was to create a mechanism that didn't require any changes in any class ( for example I didn't want to have to implement any factory base class and stuff ). To use it you just have to call one macro anywhere inside any function ( and of course include proper header but this is kinda obvious ;) ).
Let's see some code. First I have implemented class CClassFactoryWorker. It's template based solution which gets new implementation for each class T. Also it stores a class name so it's gonna be easier to check if it really created an object of correct class.
template <typename T> class CClassFactoryWorker
{
public:
static T * GetClass()
{
std::cout << "returning class " << s_ClassName << std::endl;
return new T;
}
static char s_ClassName[32];
};
template <typename T> char CClassFactoryWorker<T>::s_ClassName[32];
Second part is an actual factory class. First take a look at the code below:
class CClassFactory
{
public:
typedef void * ( *ptr ) ( void );
template
{
ptr p = (ptr)(CClassFactoryWorker
strcpy( CClassFactoryWorker
s_cfl.push_back( pair
}
void * GetClass( int idx )
{
ptr p = (ptr)(pair
return p();
}
static CClassFactory s_Singleton;
static vector< pair
};
CClassFactory CClassFactory::s_Singleton;
vector< pair
As you can see, there's type definition of a function pointer. It's just generic type that I could use for casting GetClass
#define REGISTER_CLASS( cl ) \
CClassFactory::s_Singleton.RegisterClass( (cl*)NULL, #cl )
And this is all. Now you should be able to use it as below:
int main()
{
A * base = new A();
REGISTER_CLASS( A ); // registering class A
REGISTER_CLASS( B ); // registering class B
CClassFactory::s_Singleton.GetClass(0); // create object of class A ( index 0 in s_cfl )
CClassFactory::s_Singleton.GetClass(1); // create object of class B ( index 1 in s_cfl )
return 0;
}
Just in case, code I pasted in this blog is created for showing purposes and I don't guarantee it's gonna even compile ( ie. you may not have HashString() function ). I hope it's gonna help you to write your own class factory.