Choosing a template instantiation at runtime though switch in C++
<p>I have a set of functions that are templated both by an integer type <code>Index</code> and a class type <code>T</code>, that I "partially specialize" in the following manner:</p>

<pre><code>// Integer type
enum Index{One,Two,Three,Four};

// Default implementation
template&lt;int I&gt;
struct Foo{
  template&lt;typename T&gt; static void bar(const T&amp; x){ std::cout &lt;&lt;"default" &lt;&lt; endl; }
};

// Template specializations
template&lt;&gt; 
struct Foo&lt;One&gt;{
  template&lt;typename T&gt; static void bar(const T&amp; x){ std::cout &lt;&lt; "one" &lt;&lt; endl; }
};
</code></pre>

<p>This I use to select a particular index at the runtime of the program using a switch-statement (which should result in an efficient look-up table). The switch is independent of <code>T</code>:</p>

<pre><code>template&lt;typename T&gt;
void barSwitch(int k, const T&amp; x){
  switch(k){
    case ONE: Foo&lt;ONE&gt;::bar(x); break;
    case TWO: Foo&lt;TWO&gt;::bar(x); break;
    case THREE: Foo&lt;THREE&gt;::bar(x); break;
  }
}
</code></pre>

<p>This works fine, of course, but the class <code>Foo</code> is not the only class for which I would like to apply the switch. In fact, I have a lot of classes that are all templated by the same integer type. So I would like to "template" the class <code>barSwitch</code> above with the function "Foo" as well, so that I can plug in a different class or a different function. The only way I can think of to achieve this is to use a macro:</p>

<pre><code>#define createBarSwitch(f,b) \
template&lt;typename T&gt; \
void barSwitch(int k, const T&amp; x){ \
  switch(k){ \
    case ONE: f&lt;ONE&gt;::b(x); break; \
    case TWO: f&lt;TWO&gt;::b(x); break; \
    case THREE: f&lt;THREE&gt;::b(x); break; \
  }\
}
</code></pre>

<p>Is there some better, more C++ style way of doing this?</p>
