Let't suppose I have this code:
// the enumerator
enum class my_enum {
ONE,
TWO,
THREE
};
// the function
template <my_enum E>
int foo() {
return 0;
}
// a specialization
template<>
int foo<my_enum::TWO>() {
return 1;
}
I would like to write a bar
function that specializes foo
for each element of my_enum
, and that calls, at run-time, one of those functions based on the value of an argument of bar
. The simplest solution is to write a switch and manually adding all the cases:
int bar(my_enum value) {
switch (value) {
using m = my_enum;
case m::ONE:
return foo<m::ONE>();
case my_enum::TWO:
return foo<m::TWO>();
case my_enum::THREE:
return foo<m::THREE>();
}
}
with some additional tricks to handle a unexpected value adding a default value of the switch. Unfortunately, for very long enumerators this solution brings to very long and redundant code, that is difficult to be maintained.
Is there any metaprogramming solution to simplify this code, for example using Boost Hana or Boost MPL?