title: C++11: Compile Time Calculation of Array
body: <p>Suppose I have some constexpr function f:</p>
  
  <pre><code>constexpr int f(int x) { ... }
  </code></pre>
  
  <p>And I have some const int N known at compile time:</p>
  
  <p>Either</p>
  
  <pre><code>#define N ...;
  </code></pre>
  
  <p>or</p>
  
  <pre><code>const int N = ...;
  </code></pre>
  
  <p>as needed by your answer.</p>
  
  <p>I want to have an int array X:</p>
  
  <pre><code>int X[N] = { f(0), f(1), f(2), ..., f(N-1) }
  </code></pre>
  
  <p>such that the function is evaluated at compile time, and the entries in X are calculated by the compiler and the results are placed in the static area of my application image exactly as if I had used integer literals in my X initializer list.</p>
  
  <p>Is there some way I can write this? (For example with templates or macros and so on)</p>
  
  <p><strong>Best I have: (Thanks to Flexo)</strong></p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;array&gt;
  using namespace std;
  
  constexpr int N = 10;
  constexpr int f(int x) { return x*2; }
  
  typedef array&lt;int, N&gt; A;
  
  template&lt;int... i&gt; constexpr A fs() { return A{{ f(i)... }}; }
  
  template&lt;int...&gt; struct S;
  
  template&lt;int... i&gt; struct S&lt;0,i...&gt;
  { static constexpr A gs() { return fs&lt;0,i...&gt;(); } };
  
  template&lt;int i, int... j&gt; struct S&lt;i,j...&gt;
  { static constexpr A gs() { return S&lt;i-1,i,j...&gt;::gs(); } };
  
  constexpr auto X = S&lt;N-1&gt;::gs();
  
  int main()
  {
          cout &lt;&lt; X[3] &lt;&lt; endl;
  }
  </code></pre>