Obviously the code below doesn't compile in C++. But I have a case where I'd like to parameterize a class with zero or more data items based on template parameters.
Is there any way I can declare a class whose data members depend on variadic template parameters so I can access each of them? or some other way to achieve what I'd like?
This came up in a real program which I've solved an entirely different way but now I'm interested in the more abstract problem of how I might have done this.
template <typename... Types> class Data { // Declare a variable of each type in the parameter pack // This is NOT valid C++ and won't compile... Types... items; }; struct Item1 { int a; }; struct Item2 { float x, y, z; }; struct Item3 { std::string name; } int main() { Data<Item1, Item2> data1; Data<Item3> data2; }
A variadic template is a class or function template that supports an arbitrary number of arguments. This mechanism is especially useful to C++ library developers: You can apply it to both class templates and function templates, and thereby provide a wide range of type-safe and non-trivial functionality and flexibility.
Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue.
Parameter packs (C++11) A parameter pack can be a type of parameter for templates. Unlike previous parameters, which can only bind to a single argument, a parameter pack can pack multiple parameters into a single parameter by placing an ellipsis to the left of the parameter name.
You could use a std::tuple
#include <tuple> template <typename... Types> class Data { std::tuple<Types...> items; }; struct Item1 { int a; }; struct Item2 { float x, y, z; }; struct Item3 { std::string name; }; int main() { Data<Item1, Item2> data1; Data<Item3> data2; }
Try it here
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