How to convert variadic function arguments to array? I need something like this:
template <typename T>
struct Colordata
{
public:
T dataFirst;
T dataLast;
template <typename... Ta>
Colordata(Ta... args)
{
constexpr std::size_t n = sizeof...(Ta);
std::cout << n << std::endl;
dataFirst = (args..)[0];
dataLast = (args...)[n - 1];
return;
}
};
int main(int argc, char const *argv[])
{
auto a = Colordata<float>(1.0f, 2.2f, 3.3f, 4.3f, 5.5f);
return 0;
}
I tried to use variadic arguments as T args, ...
and use functions from stdarg.h
but then I can't get the count of arguments.
You can't convert a parameter pack into an array. You could create an array from one, but that would copy, and that would be wasteful. Instead, we can "convert" the parameter pack into a tuple
of references, and then use get
to index into that tuple. That would look like
template <typename... Ta>
Colordata(Ta... args)
{
constexpr std::size_t n = sizeof...(Ta);
static_assert(n >= 1, "must pass at least one argument");
std::cout << n << std::endl;
auto& tuple = std::tie(args...);
dataFirst = std::get<0>(tuple)
dataLast = std::get<n - 1>(tuple);
}