I am new to C++ parameter pack expansion, and I have been confused about the position of ...
(ellipsis) for a long time, eg:
template <typename... Args>
void func(Args&&... args) {
// ...
std::forward<Args>(args)...;
// ...
}
Why isn't there std::forward<Args>(args...)
? What is the rule I should follow?
Check out https://en.cppreference.com/w/cpp/language/parameter_pack, particularly the "Pack expansion" section.
Basically, the "..." in the pack expansion is almost like a macro: it creates more source code, in a way. Whatever is before the "..." just gets repeated for each argument (and the pack-name replaced with said argument), so something like func(args...)
would be expanded as "func(a, b, c)", while func(args)...
would turn into "func(a), func(b), func(c)".
std::forward
just takes one argument and produces one forwarded item: func(std::forward(args)...)
will turn into a list of individual forwards: func(std::forward(a), std::forward(b), std::forward(c))
. So, it takes a list of arguments, and produces a list of forwarded arguments