Note that there are some explanatory texts on larger screens.

plurals
  1. POtrying to force static object initialization
    text
    copied!<p>I am trying to initialize a static object without success. The purpose is to automatically register a factory class in a repository (which is a singleton).</p> <p>I've already had a look at: <a href="https://stackoverflow.com/questions/6420985/how-to-force-a-static-member-to-be-initialized">How to force a static member to be initialized?</a></p> <p>One of the comments says that (there is also an example that I've followed): </p> <blockquote> <p>I read it up in the C++ standard (14.7.1): Unless a member of a class template or a member template has been explicitly instantiated or explicitly specialized, the specialization of the member is implicitly instantiated when the specialization is referenced in a context that requires the member definition to exist; in particular, the initialization (and any associated side-effects) of a static data member does not occur unless the static data member is itself used in a way that requires the definition of the static data member to exist.</p> </blockquote> <p>So I'm trying to do something similar but I haven't manage to force the object initialization. Here is the code. I don't know what I'm missing. This is the template I'm using.</p> <pre><code>namespace my_lib { template &lt;typename T&gt; struct FactoryHelper { FactoryHelper (); static FactoryHelper&lt;T&gt; _helper; }; } </code></pre> <p>And this is the macro that the user of the library would use to define the factory class and, at the same time, register an object in the repository:</p> <pre><code>#define CREATE_FACTORY(ClassName)\ namespace my_lib\ {\ class ClassName##Factory;\ template&lt;&gt; FactoryHelper&lt;ClassName##Factory&gt;::FactoryHelper () { std::cout &lt;&lt; "object initialized!" &lt;&lt; std::endl; }\ template&lt;&gt; FactoryHelper&lt;ClassName##Factory&gt; FactoryHelper&lt;ClassName##Factory&gt;::_helper;\ struct ClassName##Factory : public FactoryBase&lt;ClassName&gt; {\ ...\ };\ } </code></pre> <p>The previous code is defined in a header file (Factory.h). </p> <p>In a .cpp file (Example.cpp), I have:</p> <pre><code>CREATE_FACTORY(UnitTestExample) ... </code></pre> <p>When I execute the program, I cannot see the message that the constructor prints when it is invoked. Any help is more than welcome.</p> <p>Thanks in advance.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload