Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare member variables from variadic template parameter

Tags:

c++

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; } 
like image 883
jcoder Avatar asked Nov 24 '16 08:11

jcoder


People also ask

What is Variadic template in C++?

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.

Which of the following are valid reasons for using variadic templates in C++?

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.

What is parameter pack in c++?

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.


1 Answers

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

like image 75
Jonas Avatar answered Sep 17 '22 19:09

Jonas