2015-05-14 21 views
6

Mam kod symulacji, w którym chcę wykonać pewną konfigurację w czasie kompilacji: Na przykład, muszę zdefiniować wymiar, typ danych i klasę zawierającą operacje niskiego poziomu (czas kompilacji dla inliningu).Jak przechowywać parametry szablonu w czymś podobnym do struktury?

Coś jak:

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

pierwsze, jest to bardzo irytujące, aby zapisać cały zestaw parametrów dla każdej klasy. Po drugie, co gorsza, być może trzeba wprowadzić dodatkowy parametr i będę musiał zmienić wszystkie klasy.

Czy jest coś takiego jak struct dla parametrów szablonu?

Coś

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

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

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

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

Odpowiedz

9

Jasne, zrób szablon klasy, która udostępnia aliasy dla swoich typów i static element dla int.

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

Wtedy można go używać tak:

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; 
Powiązane problemy