Search code examples
c++variadic-templates

What does the syntax of '...' after the call to std::forward mean?


The function std::forward is declared like so:

template< class T >
T&& forward( typename std::remove_reference<T>::type& t ) noexcept;

Meaning it takes a single argument of type std::remove_reference<T>::type&.

However, std::forward can also be used with variadic arguments:

template <typename... Args>
void f(Args... args)
{
    q(std::forward<Args>(args)...);
}

I understand variadic templates and unpacking them.

However, I don't understand the syntax of ... coming "after " the call to std::forward.

What does this syntax mean precisely? Why does it work? Can it be used with functions other than std::forward?


Solution

  • This is what is called pack expansion. It expands the parameter pack out with commas between each member of the pack so

    q(std::forward<Args>(args)...);
    

    says that for each member of the parameter pack args apply std::forward to it. The resulting code would look like

    q(std::forward<Args>(args1), std::forward<Args>(args2), ..., std::forward<Args>(argsN));
    

    This works with any expression, it doesn't just apply to std::forward. For instance you could add some value to each parameter like

    q((args + 1)...);
    

    and that would expand to

    q((args1 + 1), (args2 + 1), ..., (argsN + 1));