Note that there are some explanatory texts on larger screens.

plurals
  1. PORecursive templates don't work as expected with static variables
    primarykey
    data
    text
    <p>The code</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; using namespace std; template&lt;int n&gt; struct Fibo { static int x; }; template&lt;&gt; int Fibo&lt;0&gt;::x = 1; template&lt;&gt; int Fibo&lt;1&gt;::x = 1; template&lt;int n&gt; int Fibo&lt;n&gt;::x = Fibo&lt;n-1&gt;::x + Fibo&lt;n-2&gt;::x; //marked line int main() { cout &lt;&lt; Fibo&lt;5&gt;::x &lt;&lt; endl; cout &lt;&lt; Fibo&lt;4&gt;::x &lt;&lt; endl; cout &lt;&lt; Fibo&lt;3&gt;::x &lt;&lt; endl; cout &lt;&lt; Fibo&lt;2&gt;::x &lt;&lt; endl; cout &lt;&lt; Fibo&lt;1&gt;::x &lt;&lt; endl; cout &lt;&lt; Fibo&lt;0&gt;::x &lt;&lt; endl; return 0; } </code></pre> <p>outputs</p> <pre class="lang-cpp prettyprint-override"><code>0 0 1 2 1 1 </code></pre> <p>in VC++. (According to user <a href="https://stackoverflow.com/users/952747/m-m">M M.</a> it compiles as expected in gcc). When the compiler gets to the marked line with <code>n=5</code> it doesn't compile that same line again for <code>n=4</code>, but just treats <code>Fibo&lt;4&gt;::x</code> as if it were declared with</p> <pre class="lang-cpp prettyprint-override"><code>template&lt;&gt; int Fibo&lt;4&gt;::x; // x defaults to 0 </code></pre> <p>Why is that? Why does it work as expected when using</p> <pre class="lang-cpp prettyprint-override"><code>template&lt;int n&gt; struct Fibo { enum { x = Fibo&lt;n-1&gt;::x + Fibo&lt;n-2&gt;::x }; }; template&lt;&gt; struct Fibo&lt;0&gt; { enum { x = 1 }; }; template&lt;&gt; struct Fibo&lt;1&gt; { enum { x = 1 }; }; </code></pre> <p>instead, but not with a static variable? And how do you fix the first code (without <code>enum</code>)?</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.
 

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