I have a template function where the template parameter is an integer. In my program I need to call the function with a small integer that is determined at run time. By hand I can make a table, for example:
void (*f_table[3])(void) = {f<0>,f<1>,f<2>};
and call my function with
f_table[i]();
Now, the question is if there is some automatic way to build this table to arbitrary order. The best I can come up with is to use a macro
#define TEMPLATE_TAB(n) {n<0>,n<1>,n<2>}
which at leasts avoids repeating the function name over and over (my real functions have longer names than "f"). However, the maximum allowed order is still hard coded. Ideally the table size should only be determined by a single parameter in the code. Would it be possible to solve this problem using templates?
It can be done by 'recursive' dispatching: a template function can check if it's runtime argument matches it's template argument, and return the target function with the template argument.
#include <iostream>
template< int i > int tdispatch() { return i; }
// metaprogramming to generate runtime dispatcher of
// required size:
template< int i > int r_dispatch( int ai ) {
if( ai == i ) {
return tdispatch< i > ();
} else {
return r_dispatch< i-1 >( ai );
}
}
template<> int r_dispatch<-1>( int ){ return -1; }
// non-metaprogramming wrapper
int dispatch( int i ) { return r_dispatch<100>(i); }
int main() {
std::cout << dispatch( 10 );
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With