I have a bunch of classes all inheriting from the same Base class. I'd like to register them in a ClassRegistry which is holds a map of [name=>factoryForThisClass].
To do this I had an idea but it's not working and I don't understand why:
#include <typeinfo>
#include <string>
#include <map>
#include <iostream>
template< typename T >
class declare_type
{
static int n;
};
struct GenericClassFactory
{
~GenericClassFactory() {};
virtual void* create( const std::string& rstrClassName ) = 0;
};
template <typename T>
struct ClassFactory : public GenericClassFactory
{
virtual void* create( const std::string& rstrClassName )
{
return new T();
}
};
class ClassRegister
{
public:
virtual ~ClassRegister()
{
}
template< typename T >
static int declare( const std::string& rstrClassName = typeid(T).name() )
{
std::cout << "ClassRegister::declare( " << rstrClassName << " )\n";
return 42;
}
static void create( const std::string& rstrClassName )
{
std::cout << "ClassRegister::create( " << rstrClassName << " )\n";
}
private:
};
template< typename T >
int declare_type<T>::n = ClassRegister::declare<T>();
template< typename T >
class BaseClass
{
declare_type<T> m_declaration;
};
class SomeClass : public BaseClass<SomeClass>
{
public:
void meow();
};
//template class declare_type<SomeClass>;
int main( void )
{
ClassRegister::create( "9SomeClass" );
return 0;
}
in my understanding, having SomeClass inheriting BaseClass<SomeClass>
instanciates declare_type<SomeClass>
but it doesn't ...
note that it does work if I add:
template class declare_type<SomeClass>;
In that case I don't even need the member in BaseClass, but it is a lot less "magic" as there is one such line to write for each class to declare ....
P.S: to be clear "it doesn't work" means ClassRegister::declare() is never called, as opposed to "it works" meaning ClassRegister::declare() is called before main and I can use the ClassRegistry properly.
P.S.2: OK: http://ideone.com/Af49Pb KO: http://ideone.com/ZMSSJW, only diff is line 66