title: C++ template for unrolling a loop using a switch?
body: <p>My question is similar to <a href="https://stackoverflow.com/questions/1099427/can-one-unroll-a-loop-when-working-with-an-integer-template-parameter/1100358#1100358">Can one unroll a loop when working with an integer template parameter?</a> but I want to mix compile time and runtime. Specifically, I know at compile time a constant <code>NBLOCK</code> and I want to write a switch on a variable <code>start_block</code> which is only known at runtime where <code>NBLOCK</code> is the number of entries in the switch. Here is what I got using macros:</p>
  
  <pre><code>#define CASE_UNROLL(i_loop)         \
    case i_loop : \
      dst.blocks[i_loop+1] -= (load_unaligned_epi8(srcblock) != zero) &amp; block1; \
      srcblock += sizeof(*srcblock);
  
    switch(start_block)
      {
        CASE_UNROLL(0);
  #if NBLOCKS &gt; 2
        CASE_UNROLL(1);
  #endif
  #if NBLOCKS &gt; 3
        CASE_UNROLL(2);
  #endif
  #if NBLOCKS &gt; 4
        CASE_UNROLL(3);
  #endif
  ...
  ...
  #if NBLOCKS &gt; 15
        CASE_UNROLL(14);
  #endif
  #if NBLOCKS &gt; 16
  #error "Too many blocks"
  #endif
      }
  </code></pre>
  
  <p>I find it very ugly. Especially if I want to raise the bound from 16 to 32. </p>
  
  <p>I would like to know if it is possible to write that using some template meta programming. The hard part is that for performance reasons it is crucial that the switch is compiled with a jump table than a sequence of nested conditional.       </p>
  
  <p>Note that the question is very similar to <a href="https://stackoverflow.com/questions/7381805/c-c11-switch-statement-for-variadic-templates">C++/C++11 - Switch statement for variadic templates?</a> but as far as I understand the solution proposed here is to remove the switch by using a mixed compile/tun time initialized functions pointer array. I can't pay the prince a calling a function here.</p>
  
  <p>I'm working with GCC if some nasty extensions is needed. </p>