2015-05-14 69 views
6

我有一个模拟代码,我想在编译时进行一些配置:例如,我需要定义维,数据类型和包含低级操作(内联编译时)的类。如何将模板参数存储在类似结构的东西中?

喜欢的东西:

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{ ... } 

回答

9

当然,做一个类模板提供别名为你的类型,并为您的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; 
相关问题