Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to force a static member to be initialized?
    text
    copied!<p>Consider this example code:</p> <pre><code>template&lt;class D&gt; char register_(){ return D::get_dummy(); // static function } template&lt;class D&gt; struct Foo{ static char const dummy; }; template&lt;class D&gt; char const Foo&lt;D&gt;::dummy = register_&lt;D&gt;(); struct Bar : Foo&lt;Bar&gt; { static char const get_dummy() { return 42; } }; </code></pre> <p>(<a href="http://ideone.com/YuiG6" rel="nofollow noreferrer">Also on Ideone</a>.)</p> <p>I'd expect <code>dummy</code> to get initialized as soon as there is a concrete instantiation of <code>Foo</code>, which I have with <code>Bar</code>. <a href="https://stackoverflow.com/questions/1819131/c-static-member-initalization-template-fun-inside">This question</a> (and the standard quote at the end) explained pretty clear, why that's not happening.</p> <blockquote> <p>[...] 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>Is there any way to <em>force</em> <code>dummy</code> to be initialized (effectively calling <code>register_</code>) <em>without</em> any instance of <code>Bar</code> or <code>Foo</code> (no instances, so no constructor trickery) and without the user of <code>Foo</code> needing to explicitly state the member in some way? Extra cookies for not needing the derived class to do anything.</p> <hr> <p><strong>Edit</strong>: <a href="http://ideone.com/pTI77" rel="nofollow noreferrer">Found a way</a> with minimal impact on the derived class:</p> <pre><code>struct Bar : Foo&lt;Bar&gt; { // vvvvvvvvvvvv static char const get_dummy() { (void)dummy; return 42; } }; </code></pre> <p>Though, I'd still like the derived class not having to do that. :|</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