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{ ... }
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.
8. Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With