c++ - 多个模板<int>函数的特化

标签 c++ templates

我正在运行的模拟要求我为 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)()>没有做我想做的事,因为 funtemplate<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/

相关文章:

c# - 非托管 C++ 代码上的 NullReferenceException

c++ - 如何在检测习语中要求精确的函数签名?

c++ - 将模板化方法定义移出头文件的优雅方法

C++ 模板错误?

c++ - 无法推导模板参数

c++ - 未解析的非模板方法被正确实例化的模板方法调用

c++ - 从一组集合 { {..}, {..}, {..} } 中挑选数字集合 {1,2,3} 使得所有元素都是唯一的

c++ - 从固定流水线转向现代 OpenGL

c++ - 如何组合三个变量以使用boost asio发送?

c++ - "uses of target_link_libraries must be either all-keyword or all-plain"