title: Template metaprogramming recursion up limits?
body: <p>I am writing a very simple template class using Metaprogramming to compute sum in compile time, as below:</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  using namespace std;
  
  template&lt;int N&gt;
  class Sum
  {
      public:
          enum {value = N + Sum&lt;N-1&gt;::value };
  };
  
  template&lt;&gt;
  class Sum&lt;0&gt;
  {
      public:
          enum {value = 0};
  };
  
  
  int main()
  {
      cout &lt;&lt; Sum&lt;501&gt;::value &lt;&lt; endl;
  }
  </code></pre>
  
  <p>The interesting thing is:</p>
  
  <ul>
  <li>When I print Sum&lt;500> and below, it works fine </li>
  <li><p>When it comes to Sum&lt;501>, the compile failed with:  </p>
  
  <blockquote>
    <p>sum.cpp:9:   instantiated from <code>Sum&lt;500&gt;' sum.cpp:9:   instantiated
    from</code>Sum&lt;501>' sum.cpp:22:   instantiated from here</p>
    
    <p>sum.cpp:9: error: incomplete type <code>Sum&lt;1&gt;' used in nested name
    specifier sum.cpp:9: error: enumerator value for</code>value' not integer
    constant</p>
  </blockquote></li>
  <li><p>Sum&lt;501> will report error of Sum&lt;1>, Sum&lt;502> will report error of Sum&lt;2>, the difference is always 2, it seems to me the compiler has a limit resource of 500.</p></li>
  </ul>
  
  <p>Any idea about this? and is their a way to break this limits? </p>
  
  <p>Thanks.</p>
  
  <p><em>Edit:</em><br>
  Thanks guys, the point is not about the algorithm, but rather the compiler limitation - I know there is an easy way to get sum:)</p>
  
  <p><em>Edit2:</em>    </p>
  
  <ul>
  <li>Use gcc 4.6 +, the error message is much more helpful
  
  <blockquote>
    <p>sum.cpp:9:14: error: template instantiation depth exceeds maximum of
    1024 (use -ftemplate-depth= to increase the maximum) instantiating
    ‘class Sum&lt;1>’ sum.cpp:9:14:   recursively instantiated from
    ‘Sum&lt;1024>’ sum.cpp:9:14:   instantiated from ‘Sum&lt;1025>’
    sum.cpp:22:22:   instantiated from here</p>
  </blockquote></li>
  </ul>
  
  <p>so yes, use ftemplate-depth is the right way. But how about in windows? the uplimits for VC9.0 is 499, and seems there is no option to set the template depth, see <a href="http://msdn.microsoft.com/en-us/library/fwkeyyhe(v=VS.71).aspx" rel="noreferrer">here</a></p>