如何为编译时已知的参数的多个值编译函数
How to compile a function for multiple values of a parameter known in compile-time
我正在编写一个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);
}
我希望在你的实际代码中有真正的好处:)
相关文章:
- 非类型指针和引用模板参数,以及在编译时如何/为什么解析它们.c++
- 根据编译时参数在 C 中重复代码
- 使用 SFINAE 作为模板参数的编译时递归
- 使用带有 ref 参数的成员函数创建线程时出现编译错误
- 使用 std::enable_if 限制派生类的模板参数时出现编译错误
- 带有自动参数的函数使用 GCC 编译,但不使用 Visual C++ 编译
- 为什么我的递归可变参数模板无法编译?
- 知道模板参数在编译时是否为 const char*?
- 可变参数模板未在 MSVC 中编译?
- 将函数类型作为模板参数传递不会编译
- 线程构造函数周围的可变参数模板包装器无法编译
- 编译错误:临时对象构造函数中缺少参数
- 在编译时收集模板参数
- 有没有办法根据命令行参数定义数组大小?运行时与编译时实例化?
- C++模板-基于参数编译成员函数
- C++编译时检查是否可以用某种类型的参数调用重载函数
- Visual Studio代码:C 编译参数-O
- Clang 无法使用模板元编程编译参数包扩展
- 如何更改和设置Rcpp编译参数
- Jamfile的可移植编译参数