I have a set of functions that are templated both by an integer type Index
and a class type T
, that I "partially specialize" in the following manner:
// Integer type
enum Index{One,Two,Three,Four};
// Default implementation
template<int I>
struct Foo{
template<typename T> static void bar(const T& x){ std::cout <<"default" << endl; }
};
// Template specializations
template<>
struct Foo<One>{
template<typename T> static void bar(const T& x){ std::cout << "one" << endl; }
};
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 T
:
template<typename T>
void barSwitch(int k, const T& x){
switch(k){
case ONE: Foo<ONE>::bar(x); break;
case TWO: Foo<TWO>::bar(x); break;
case THREE: Foo<THREE>::bar(x); break;
}
}
This works fine, of course, but the class Foo
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 barSwitch
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:
#define createBarSwitch(f,b) \
template<typename T> \
void barSwitch(int k, const T& x){ \
switch(k){ \
case ONE: f<ONE>::b(x); break; \
case TWO: f<TWO>::b(x); break; \
case THREE: f<THREE>::b(x); break; \
}\
}
Is there some better, more C++ style way of doing this?