Michael
Michael

Reputation: 7819

How to store template parameters in something like a struct?

I have a simulation code where I want to do some configuration at compile time: For example, I need to define the dimension, the datatype and a class containing the low level operations (compile-time for inlining).

Something like:

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

First, it's extremely annoying to write the whole parameter set for each class. Second, even worse, it could be that an additional parameter has to be introduced and I would have to change all classes.

Is there something like a struct for template parameters?

Something like

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

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

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

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

Upvotes: 8

Views: 1177

Answers (1)

TartanLlama
TartanLlama

Reputation: 65630

Sure, make a class template which provides aliases for your types and a static member for your int.

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

Then you can use it like this:

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;

Upvotes: 12

Related Questions