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