1

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 as 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;
}
Farzad
  • 3,288
  • 2
  • 29
  • 53
  • If it's known at runtime, you can't have it as a template parameter. – jrok Jun 05 '14 at 19:24
  • I know. What I'm trying to say is that I cannot use `template` but I want to use something similar to reduce the amount of copied code, with the pre-known information that `a` would be in the range `[1,5]`. – Farzad Jun 05 '14 at 19:26
  • You have two choices to deal with the `a`. 1. Check the value of `a` before calling `foo`. 2. Throw an exception from `foo` is `a` is not within the expected range. – R Sahu Jun 05 '14 at 19:26
  • 1
    You can specialize it for the values you need and use typedef's – imreal Jun 05 '14 at 19:27
  • To achieve what you want at runtime you could think of a solution like `std::map` (i.e. using function pointers or functor objects). – πάντα ῥεῖ Jun 05 '14 at 19:28
  • @Farzad: I still don't understand why you cannot just make `a` a regular (non-template) parameter. – Christian Hackl Jun 05 '14 at 19:34
  • @ChristianHackl I want to have different compiled versions of a function. The reason behind it relates to my code. I'm going to probably use my function for a CUDA program and knowing a variable at compile time reduces the condition checks, and may free up some registers. – Farzad Jun 05 '14 at 19:39

1 Answers1

4

Something like this comes to mind:

template <int a> int foo_impl(int b){
    return a+b;
}

int (*foos[5])(int) = {
   foo_impl<1>,
   foo_impl<2>,
   foo_impl<3>,
   foo_impl<4>,
   foo_impl<5>
};

int foo(int a, int b)
{
    return (foos[a-1])(b);
}

I hope there's are real benefit in your real code for this :)

jrok
  • 54,456
  • 9
  • 109
  • 141