I'm currently trying to implement some functionality as below with template metaprogramming
typedef void (*function)(void*);
function function_array[/* total size of type list */];
...
template<typename T>
void some_func(void*)
{
// do something with type T
}
...
function_array[0] = &some_func<type_0>;
function_array[1] = &some_func<type_1>;
function_array[2] = &some_func<type_2>;
...
function_array[n] = &some_func<type_n>;
My intention is to implement dynamic dispatch mechanism for type by integer index of type.
It seems that it can be achieved by using variadic template mechanism ( C++/C++11 - Switch statement for variadic templates? ), but currently I can't use a compiler that supports variadic template.
So I've tried to workaround via using type list (in the modern C++ design) and template recursion as a conceptual code like below.
template<typename list, typename function>
struct type_dispatch
{
type_dispatch() { init(); }
template<typename typelist>
void init();
template<typename head, typename tail>
void init(cell<head, tail>&)
{
// setting dispatch array with templated function
function_array[index_of<list, head>::value] = &function<head>;
init(tail());
}
void init(null&) {}
// functor array which size is equal to the size of type list
function function_array[size_of<list>::value];
};
Of course, above code won't be compiled properly. How can I implement this functionality?