Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm not sure if the initialization order of the <em>static variables</em> of <code>template&lt;int n&gt; int Fibo&lt;n&gt;::x = Fibo&lt;n-1&gt;::x + Fibo&lt;n-2&gt;::x;</code> is specified...</p> <p>You may write this:</p> <pre><code>template &lt;int N&gt; struct Fibo { int operator()() const { static int x = Fibo&lt;N - 1&gt;()() + Fibo&lt;N - 2&gt;()(); return x; } }; template &lt;&gt; struct Fibo&lt;1&gt; { int operator()() const { static int x = 1; return x; } }; template &lt;&gt; struct Fibo&lt;0&gt; { int operator()() const { static int x = 1; return x; } }; </code></pre> <p>The dependencies are respected.</p> <p>[Edit]</p> <p>In a case where the value may be modified (according to your comment), you may use similar technique but returning reference:</p> <pre><code>template &lt;int N&gt; struct Fibo { private: int&amp; operator()() { static int x = Fibo&lt;N - 1&gt;()() + Fibo&lt;N - 2&gt;()(); return x; } public: int operator()() const { return const_cast&lt;Fibo&amp;&gt;(*this)(); } // This change Fibo&lt;0&gt; and Fibo&lt;1&gt; and then update value up to Fibo&lt;N&gt;. int operator(int fibo0, int fibo1) { int n_1 = Fibo&lt;N - 1&gt;()(fibo1, fibo2); (*this)() = n_1 + Fibo&lt;N - 2&gt;()(); } }; template &lt;&gt; struct Fibo&lt;1&gt; { private: int&amp; operator()() { static int x = 1; return x; } public: int operator()() const { return const_cast&lt;Fibo&amp;&gt;(*this)(); } void operator(int fibo0, int fibo1) { Fibo&lt;0&gt;()(fibo0); (*this)() = fibo1; } }; template &lt;&gt; struct Fibo&lt;0&gt; { private: int&amp; operator()() { static int x = 1; return x; } public: int operator()() const { return const_cast&lt;Fibo&amp;&gt;(*this)(); } void operator(int fibo0) { (*this)() = fibo0; } }; </code></pre>
 

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