我正在运行的模拟要求我为 int
使用模板参数(D = 我的系统的维度)。一个典型的模拟函数是
template <int D> void simulation();
当我想专门化这个模板时,我使用一个开关
switch(d){
case 2:
simulation<2>();
break;
case 3:
simulation<3>();
break;
// etc.
}
只要我有一个模拟功能,就可以了。但是想象一下我有 10 个 then (simul1, simul2, ... simul10),d 可以从 2 到 10。我必须写十次相同的开关!
我想知道是否有可能分解它,并得到类似的东西:
template <void (*fun)()> runSimulation(int d){
switch(d){
case 2:
fun<2>();
}
}
当然<void (*fun)()>
没有做我想做的事,因为 fun
是 template<int>
.有办法吗?
最佳答案
当你可以将模拟函数更改为一个带有静态方法的类时:
struct sim1
{
template<int D> static void apply();
};
然后应该可以执行以下操作:
template <typename Sim> runSimulation(int d){
switch(d){
case 2:
Sim::template apply<2>();
case 3:
Sim::template apply<3>();
// ...
}
}
这是通用的,可以用 runSimulation<sim1>(d);
调用或 runSimulation<sim2>(d);
等等
关于c++ - 多个模板<int>函数的特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31062191/