如何为编译时已知的参数的多个值编译函数

How to compile a function for multiple values of a parameter known in compile-time

本文关键字:编译 参数 函数      更新时间:2023-10-16

我正在编写一个c++函数,目前通过模板接收参数。这个函数很复杂,但是为了简化问题,可以考虑这样一个函数:

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

但是在最后的程序中,上述函数中的a在运行时(而不是编译时)是已知的,但是用户被迫提供范围为1到5的a。换句话说,我在编译时可能不知道a,但我确信a将是1,2,3,4或5中的一个。
我如何为不同的a分别编译上述函数5次,并在运行时选择运行适当的一个?
一种解决方案是定义不同版本的foo,如foo_1, foo_2,…编译不同的a,但它明显增加了复制代码的数量,特别是当函数很大的时候。有没有更好的解决办法?

编辑
我的目标是避免类似下面的东西,并在运行时有一个switch来决定使用哪个。

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;
}

我想到了这样的东西:

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);
}

我希望在你的实际代码中有真正的好处:)