Home > OS >  Is it possible to have a variadic argument list for a template or automatically generated specificat
Is it possible to have a variadic argument list for a template or automatically generated specificat

Time:10-11

Let's say I have the following tuple:

std::tuple<int, int, int> setVals(int val)
{
   return std::make_tuple(val, val, val);
}

It is really nice to have structured bindings with this: auto [x, y, z] = setVals(42);

Would it be possible to have some kind of variadic signature for setVals, so I could do structured bindings with any number of variables? For instance, auto [x, y] = setVals(42); or auto [x, y, z, x2, y2, z2] = setVals(42);

I know that I could just use a variadic function template where I could just declare some ints and pass them in as references, but the structured bindings are so convenient that I was wondering if something like I just showed is possible. I'm sorry if this question is bad.

CodePudding user response:

You can create a function like what you want but you have to specify the number of elements the tuple will have as a template parameter. That would give you code like:

// does the actual creation
template <typename T, std::size_t... Is>
auto create_tuple_helper(const T& initial_value, std::index_sequence<Is...>)
{
    // this ueses the comma expression to discard Is and use initial_value instead for each element
    return std::tuple{(void(Is), initial_value)...};
    // void(Is) is used to get rid of a warning for an unused value
}

// this is a wrapper and makes it easy to call the helper function
template <std::size_t N, typename T>
auto create_tuple(const T& initial_value)
{
    return create_tuple_helper(initial_value, std::make_index_sequence<N>{});
}

int main()
{
    auto [a, b, c, d] = create_tuple<4>(42);
    std::cout << d;
}

Live example

  • Related