c++ - 如何将模板参数存储在结构之类的东西中?

标签 c++ templates

我有一个模拟代码,我想在编译时进行一些配置:例如,我需要定义维度、数据类型和包含低级操作的类(内联的编译时)。

类似于:

template <int DIMENSION, class DATATYPE, class OPERATIONS>
class Simulation{ ... }

template <int DIMENSION, class DATATYPE, class OPERATIONS>
class SimulationNode{ ... }

template <int DIMENSION, class DATATYPE, class OPERATIONS>
class SimulationDataBuffer{ ... }

首先,为每个类编写整个参数集非常烦人。其次,更糟糕的是,可能必须引入一个额外的参数,我将不得不更改所有类。

是否有类似模板参数的结构?

有点像

struct {
  DIMENSION = 3;
  DATATYPE = int;
  OPERATIONS = SimpleOps;
} CONFIG;

template <class CONFIG>
class Simulation{ ... }

template <class CONFIG>
class SimulationNode{ ... }

template <class CONFIG>
class SimulationDataBuffer{ ... }

最佳答案

当然,制作一个类模板,为您的类型提供别名,并为您的 int 提供一个 static 成员。

template <int DIMENSION, class DATATYPE, class OPERATIONS>
struct Config
{
    static constexpr int dimension = DIMENSION;
    using datatype = DATATYPE;
    using operations = OPERATIONS;
};

然后你可以像这样使用它:

template <class CONFIG>
class Simulation{
    void foo() { int a = CONFIG::dimension; }
    typename CONFIG::operations my_operations;
}

using my_config = Config<3, int, SimpleOps>;
Simulation<my_config> my_simulation;

关于c++ - 如何将模板参数存储在结构之类的东西中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30233776/

相关文章:

c++ - 双模板函数重载失败

c++ - 根据模板参数使用不同的函数集(C++ 特征?)

c++ - 重构现有的包装器类以使用与包装器本身相同的构造函数参数来包装 T

c++ - 对象在返回之前销毁了自己? C++

c++ - "simple"C++ 解析器

c++ - 运行C++程序时出现"The system cannot find the file specified"

c++ - 在函数模板中打包扩展调用模板化方法

c++ - 在模板实例化中使用运行时值

c++ - 嵌套模板和静态成员初始化

c++ - 如果使用 vector 作为容器,如何弹出队列