C++ template instantiation: Avoiding long switches
You could use a variadic template, maybe like this:
#include <cstdlib>
#include <string>
int main(int argc, char * argv[])
{
if (argc != 2) { return EXIT_FAILURE; }
handle_cases<1, 3, 4, 9, 11>(std::stoi(argv[1]));
}
Implementation:
template <int ...> struct IntList {};
void handle_cases(int, IntList<>) { /* "default case" */ }
template <int I, int ...N> void handle_cases(int i, IntList<I, N...>)
{
if (I != i) { return handle_cases(i, IntList<N...>()); }
Wrapper<I> w;
w.foo();
}
template <int ...N> void handle_cases(int i)
{
handle_cases(i, IntList<N...>());
}
arg_int is a runtime parameter so there is no way to attach it directly to a template parameter. You could use some kind of handler table which would remove the switch statement here.
You'd use something like lookup_handler( int N )
returning a type handler
which might be a lambda invoking one of those template functions.
Registering all your lambdas on the table could be done recursively starting with the highest numbered one you allow.
template< unsigned N > register_lambda()
{
table.add( Wrapper<N>() );
register_lambda< N-1 >;
}
and specialise for register_lambda<0>
Then somewhere you call register_lambda<32>
say and you have registered all the numbers from 0 to 32.
One way to implement such a table is:
class lambda_table
{
typedef std::function<void()> lambda_type;
public:
void add( lambda_type );
bool lookup( size_t key, lambda_type & lambda ) const;
};
From main() or wherever you want to invoke it you have a reference to this table (call it table) then call
lambda_type lambda;
if( table.find( arg_int, lambda ) )
lanbda();
else
default_handler();
You might change this to give the table itself a default handler where none has been supplied for this number.
Although lambdas can wrap all kinds of data members you might actually want your templates to be classes in a hierarchy rather than lambdas given the data storage within them.