Search code examples
c++templatesvisual-c++variadic-templatesvariadic-functions

How do I create an std::tuple<> from a variadic template parameter?


I have a class that is declared with this template: template <typename ...Args>. In it, I have a list declared as std::vector<std::tuple<Args...>> vec; to store data entries specified by the template. I also have a function declared as follows:

void AddVertex(Args... data)
{
    // vec.push_back(std::tuple<Args...>(data));
}

In this function, I want to add a tuple of Args... to the vector. Is this possible? I have tried using the code in the comment, but the compiler gives me an error saying that "the parameter pack must be expanded in this context".

This solution doesn't work, because the template argument of the tuple is already expanded.


Solution

  • You need to expand both:

    • template parameters pack (Args...)

    and

    • function parameters pack (data...):

    so it should be:

        vec.push_back(std::tuple<Args...>(data...));
    

    Or shorter form, use make_tuple:

        vec.push_back(std::make_tuple(data...));