Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store template parameters in something like a struct?

Tags:

c++

templates

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{ ... }
like image 981
Michael Avatar asked May 14 '15 09:05

Michael


People also ask

How do you pass a parameter to a template in C++?

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

Why do we use :: template template parameter?

8. Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.

Can a template be a template parameter?

Templates can be template parameters. In this case, they are called template parameters. The container adaptors std::stack, std::queue, and std::priority_queue use per default a std::deque to hold their arguments, but you can use a different container.

Can we pass Nontype parameters to templates?

Template classes and functions can make use of another kind of template parameter known as a non-type parameter. A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument.


1 Answers

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;
like image 171
TartanLlama Avatar answered Sep 19 '22 14:09

TartanLlama