jcoder jcoder - 14 days ago 8
C++ Question

Declare member variables from variadic template parameter

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;
}

Answer

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