title: choose correct template specialization at run-time
body: <p>I have</p>
  
  <pre><code>template &lt;int i&gt; struct a { static void f (); };
  </code></pre>
  
  <p>with specializations done at different places in the code. How can I call the correct <code>a&lt;i&gt;::f</code> for an <code>i</code> known only at runtime?</p>
  
  <pre><code>void f (int i) { a&lt;i&gt;::f (); } // won't compile
  </code></pre>
  
  <p>I don't want to list all possible values of <code>i</code> in a big <code>switch</code>.</p>
  
  <p>Edit:</p>
  
  <p>I thought of something like</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  template &lt;int i&gt; struct a { static void f (); };
  
  struct regf {
    typedef void (*F)();
    enum { arrsize = 10 };
    static F v[arrsize];
    template &lt; int i &gt; static int apply (F f) {
      static_assert (i &lt; arrsize, "");
      v[i] = a&lt;i&gt;::f;
      return 0;
    }
  };
  regf::F regf::v[arrsize];
  
  template &lt;int i&gt; struct reg { static int dummy; };
  template &lt;int i&gt; int reg&lt;i&gt;::dummy = regf::apply&lt;i&gt; ();
  
  void f (int i) { return regf::v[i] (); }
  
  #define add(i) \
    template &lt;&gt; struct a&lt;i&gt; : reg&lt;i&gt; { \
      static void f () { std::cout &lt;&lt; i &lt;&lt; "\n"; } \
    };
  
  add(1)
  add(3)
  add(5)
  add(7)
  
  int main () {
    f (3);
    f (5);
  }
  </code></pre>
  
  <p>but it crashes (did I miss something to force an instantiation?), and I don't like that dummy is not <code>static const</code> (and uses memory) and of course that <code>arrsize</code> is bigger than necessary.</p>
  
  <hr>
  
  <p>Actual problem: To have a function <code>generate (int i)</code> that calls <code>a&lt;i&gt;::generate ()</code> to generate an instance of class <code>a&lt;i&gt;</code> for an <code>i</code> given only at run-time. The design (classes <code>a&lt;i&gt;</code>) is given, they inherit from a base class and more specializations of a could be added at any time anywhere in the code, but I don't want to force everyone to change my <code>generate (i)</code> manually as that could be forgotten easily.</p>