I'm writing a C++ function that at the moment receives a parameter via template. The function is complicated, but to simplify the question, consider a function like this:
template <int a> int foo(int b){
return a+b;
}
But in the final program, a
in above function will be known at runtime (not compile time) however the user is forced to provide a
in the range of 1 to 5. In other words, I may not know a
exactly in compile time but I'm sure that a
would be one of 1, 2, 3, 4, or 5.
How can I compile above function 5 times each for a different a
and at runtime choose to run the proper one?
One solution is to define different versions of foo
like foo_1
, foo_2
, ... compiled for different a
s but it obviously increases the amount of copied code especially when the function is big. Is there any better solution?
EDIT
My goal is to avoid something like below and have a switch
in runtime deciding which one to use.
int foo_1(int b){
return 1+b;
}
int foo_2(int b){
return 2+b;
}
int foo_3(int b){
return 3+b;
}
int foo_4(int b){
return 4+b;
}
int foo_5(int b){
return 5+b;
}