Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In light of your edit, you could try something like this:</p> <pre><code>#include &lt;iostream&gt; #include &lt;stdexcept&gt; using namespace std; template &lt;typename T&gt; class my_class { public: static bool s_isInitialized; my_class() { if(!s_isInitialized) { throw logic_error("must call my_function&lt;T&gt; before instantiating my_class&lt;T&gt;"); } cout &lt;&lt; "ctor ok" &lt;&lt; endl; } }; template &lt;typename T&gt; bool my_class&lt;T&gt;::s_isInitialized = false; template &lt;typename T&gt; void my_function(const char * type) { cout &lt;&lt; "initializing " &lt;&lt; type &lt;&lt; endl; my_class&lt;T&gt;::s_isInitialized = true; } int main() { my_function&lt;bool&gt;("bool"); my_class&lt;bool&gt; a; my_function&lt;int&gt;("int"); my_class&lt;int&gt; b; my_class&lt;int&gt; c; cout &lt;&lt; "now for something different" &lt;&lt; endl; my_class&lt;short&gt; d; // ctor throws // this code isn't reached } </code></pre> <p>Basically, have a flag for each template instantiation of <code>my_class&lt;T&gt;</code> which determines if the appropriate <code>my_function&lt;T&gt;</code> has been called. Initialize the flag to <code>false</code>, and set it to <code>true</code> in <code>my_function&lt;T&gt;</code>. The constructor(s) of <code>my_class&lt;T&gt;</code> then have to check the flag, and throw an exception if it's still false.</p> <p>Although the check is at runtime rather than compile-time like you wanted, the overhead is negligent. It is a single check of a boolean, which is one instruction to load the byte and one instruction for the branch. You won't pay any overhead for the branch since any half decent hardware branch predictor will always predict correctly for every instantiation of your classes (except maybe the first instantiation or two).</p> <p>Additionally, you can also add a check in <code>my_function&lt;T&gt;</code> to check that the flag hasn't already been set, and either do nothing or throw another <code>logic_error</code> (as you deem appropriate) if initialization has already occurred.</p> <p>If you are using any threading/concurrency, you will of course have to protect against concurrent access to the flag/initialization function. That will require a bit more programming overhead, but it's not hard.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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