title: Compile time evaluation of a C++ loop
body: <p>I am trying to write a C++ loop that I want evaluated at compile-time. This is because I need to use the looping variable as a template argument to initialize a class. In the very simple case it would look something like:</p>
  
  <pre><code>for (unsigned int i = 1; i &lt; 8; i++) {
    Vector&lt;i&gt; foo;
    // do something with foo
  }
  </code></pre>
  
  <p>After going through some similar StackOverflow <a href="https://stackoverflow.com/a/14248464/2037446">questions</a>, I found a way to write a static for loop recursively. Now my code looks something like this:</p>
  
  <pre><code>template &lt;unsigned int i, unsigned int end&gt;
  struct static_for {
    template &lt;typename Lambda&gt;
    void operator()(const Lambda&amp; function) const {
      if (i &lt; end) {
        function(i);
        static_for&lt;start + 1, end&gt;(function);
      }
    }
  };
  
  template &lt;int N&gt;
  struct static_for&lt;N, N&gt; {
    template &lt;typename Lambda&gt;
    void operator()(const Lambda&amp; function) const {
      // This is just to avoid the unused variable warning - does nothing.
      (void)function;
    }
  };
  </code></pre>
  
  <p>This works perfectly and as expected. In order to call this <code>static_for</code> loop I can simply write:</p>
  
  <pre><code>static_for&lt;0, 8&gt;()([](int size) {
        // some code here.
      });
  </code></pre>
  
  <p>The problem, however, is that I can still not evaluate <code>i</code> at compile time. As in I cannot create a templated object within the lambda expression:</p>
  
  <pre><code>static_for&lt;0, 8&gt;()([](int size) {
        Vector&lt;size&gt; var; // does not compile as size is not a constexpr.
      });
  </code></pre>
  
  <p>How can I make this work? My <code>static_for</code> loop has the <code>i</code> variable as a template argument which is available to it at compile time. I would like my lambda expression to receive this argument (<code>size</code>) also at compile time rather than being passed in as a runtime variable. How would this work? Conceptually this seems simple and useful as a more general language feature as well.</p>