Ensuring that a static method gets called before main()
<p>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.</p>

<p>The way that this currently works is as follows: I've got a class called <code>WorkerImplementationList</code> with a static method:</p>

<pre><code>template &lt;typename T&gt;
    WorkerImplementationList::registerWorkerFactoryMethod&lt;T&gt;(const std::string&amp;)
</code></pre>

<p>that stores a pointer to <code>T::newInstance</code> in an internal data structure that will be retrieved by the factory later. In each of the worker classes have a static int called <code>_dummyInstanceRegistrationVariable</code>. In each of the worker classes' .cc files, I have the following line (using <code>FooWorker</code> as an example):</p>

<pre><code>int FooWorker::_dummyInstanceRegistrationVariable =
    WorkerImplementationList::registerWorkerFactoryMethod&lt;FooWorker&gt;("FooWorker");
</code></pre>

<p>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 <code>main()</code>. However, when <code>FooWorker</code> is in a library (say <code>libblahapp_workers.a</code>) and the main executable links that library, it looks like <code>_dummyInstanceRegistrationVariable</code> isn't initialized until after <code>main()</code> starts (I assume it's initialized when the first instance of <code>FooWorker</code> is constructed), which is too late for my purposes.</p>

<p>I've also tried constructing a <code>WorkerImplementationRegisterer&lt;T&gt;</code> 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 <code>main()</code>; that globally-scoped object isn't constructed before <code>main()</code> begins.</p>

<p>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.</p>
