I have a collection of worker classes, and I need to be able to construct instances of these classes dynamically with a single factory. The reasoning behind this is that new worker classes are written frequently and I'd rather not have to update a factory class per worker type every time I add a new worker class.
The way that this currently works is as follows: I've got a class called WorkerImplementationList
with a static method:
template <typename T>
WorkerImplementationList::registerWorkerFactoryMethod<T>(const std::string&)
that stores a pointer to T::newInstance
in an internal data structure that will be retrieved by the factory later. In each of the worker classes have a static int called _dummyInstanceRegistrationVariable
. In each of the worker classes' .cc files, I have the following line (using FooWorker
as an example):
int FooWorker::_dummyInstanceRegistrationVariable =
WorkerImplementationList::registerWorkerFactoryMethod<FooWorker>("FooWorker");
What I'd like to have happen is for the static variable to be initialized before any instances of the class are constructed. This seems to work just fine when the worker class is compiled into the same binary that contains main()
. However, when FooWorker
is in a library (say libblahapp_workers.a
) and the main executable links that library, it looks like _dummyInstanceRegistrationVariable
isn't initialized until after main()
starts (I assume it's initialized when the first instance of FooWorker
is constructed), which is too late for my purposes.
I've also tried constructing a WorkerImplementationRegisterer<T>
object in global scope that registers the appropriate worker type when it's constructed, but here again I run into problems when the worker class is in a library external to main()
; that globally-scoped object isn't constructed before main()
begins.
Would statically linking my worker libraries solve this problem? Is there a more elegant solution that I'm missing? Any help you could give me would be greatly appreciated.