【发布时间】:2015-06-25 22:57:31
【问题描述】:
我正在运行的模拟要求我为 int 参数(D = 我的系统的维度)使用模板。一个典型的模拟函数是
template <int D> void simulation();
当我想专门化这个模板时,我会使用一个开关
switch(d){
case 2:
simulation<2>();
break;
case 3:
simulation<3>();
break;
// etc.
}
只要我有一个模拟功能,就可以了。但想象一下,我有 10 个(simul1、simul2、... simul10),d 可以从 2 变为 10。我必须写十次相同的开关!
我想知道是否可以分解它,并有类似的东西:
template <void (*fun)()> runSimulation(int d){
switch(d){
case 2:
fun<2>();
}
}
当然<void (*fun)()> 不符合我的要求,因为fun 是template<int>。有办法吗?
【问题讨论】:
-
一种选择是使用 Boost.Preprocessor 生成
case语句。 -
或者,您可以传递一个
tuple整数,并使用一些元编程让编译器迭代(=递归)相当于您的手写案例。 -
是否可以将模拟功能更改为类?喜欢:
template <int D> struct simulation { static void apply(); };?甚至struct simulation { template <int D> static void apply(); };? -
为什么不呢?您是在建议,我应该使用抽象类
Simul的继承吗?然后void runSimul(Simul& s, int d)。或者更简单? -
@styko 方法更简单,看我的回答。