I am implementing a pattern where instances of classes will be generated by factories of that class.
The factories should be registered on application start, and ideally the code to register them should be in the class definition files (i.e. not in user code).
The factory looks a bit like:
template<typename NodeType>
class Factory : public BaseFactory {
public:
shared_ptr<BaseNode> make() override {
return static_pointer_cast<BaseNode>(this->makeTyped());
}
shared_ptr<NodeType> makeTyped() {
return make_shared<NodeType>();
}
};
I also have a global map of BaseFactory's (called FactoryRegister).
My current approach is to have a class 'FactoryRegisterDeclataion' which performs the registry:
template<typename NodeType>
class FactoryRegisterDeclaration {
public:
FactoryRegisterDeclaration() {
FactoryRegister::X().add(make_shared<Factory<NodeType>>()); // X is a singleton of the FactoryRegister
}
};
and then in the c++ file for each class I do like:
FactoryRegisterDeclaration<MyNodeClass> MyNodeClassFactory = FactoryRegisterDeclaration<MyNodeClass>();
For this to work, my application must link that cpp file. However, this doesn't happen if there is no reference to MyNodeClass anywhere in the application. If there is no reference to MyNodeClass in my application, then the cpp file is never included and the factory is never registered, thereby disallowing me from ever creating the class instance.
In essence, I'm trying to put the following code at the top of the class definition cpp file which is to run at application start:
FactoryRegister::X().add(make_shared<Factory<MyNodeClass>>());
Also note that MyNodeClass is in a static library being linked by my application. My environment is Visual Studio 2013.
Ideas:
- Is it possible to force VS to link the CPP file into the static lib (perhaps it is being missed out)? Or that the application including the static lib strips the 'unused' symbols accidentally?
- Is there another pattern which would allow me to create and register the factory on application start?
Thanks and regards