2015-05-14 16 views
6

Derleme zamanında bir yapılandırma yapmak istediğim bir simülasyon kodum var: Örneğin, boyutu, veri türü ve düşük düzeyli işlemleri içeren bir sınıfı tanımlamalıyım (satır içi derleme zamanı).Şablon parametreleri bir struct gibi bir şeyde nasıl saklanır?

şey gibi:

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

Birincisi, her sınıf için tüm parametre setini yazmak için son derece sinir bozucu. İkincisi, daha da kötüsü, ek bir parametre eklenmeli ve tüm sınıfları değiştirmek zorunda kalabilecekti.

Şablon parametreleri için bir yapı gibi bir şey var mı?

şey

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

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

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

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

cevap

9

Tabii gibi, türleri için adlar sağlayan bir sınıf şablonu ve int için static üye olun.

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

Sonra bu gibi kullanabilirsiniz:

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; 
İlgili konular