SHAMELESS COPY [approved by its source]
Parameter packs can only be expanded in a strictly-defined list of contexts, and operator ,
is not one of them. In other words, it's not possible to use pack expansion to generate an expression consisting of a series of subexpressions delimited by operator ,
.
The rule of thumb is "Expansion can generate a list of ,
-separated patterns where ,
is a list delimiter." Operator ,
does not construct a list in the grammar sense.
To call a function for each argument, you can use recursion (which is the primary tool in the variadic template programmer's box):
#include <utility>
template<typename T>
void foo(T &&t){}
template<typename Arg0, typename Arg1, typename ... Args>
void foo(Arg0 &&arg0, Arg1 &&arg1, Args &&... args){
foo(std::forward<Arg0>(arg0));
foo(std::forward<Arg1>(arg1), std::forward<Args>(args)...);
}
auto main() -> int{
foo(1, 2, 3, "3");
}
USEFUL NON-COPIED INFO
Another thing you probably haven't seen in this answer is use of the &&
specifier and std::forward
. In C++, the &&
specifier can mean one of 2 things: rvalue-references, or universal references.
I won't go into rvalue-references, but to somebody working with variadic templates; universal references are a god-send.
Perfect Forwarding
One of the uses of std::forward
and universal references are perfect forwarding of types to other functions.
In your example, if we pass an int&
to foo2
it will be automatically demoted to int
because of the signature of the generated foo2
function after template deduction and if you wanted to then forward this arg
to another function that would modify it by reference, you will get undesired results (the variable won't be changed) because foo2
will be passing a reference to the temporary created by passing an int
to it. To get around this, we specify a forwarding function to take any type of reference to a variable (rvalue or lvalue). Then, to be sure that we pass the exact type passed in the forwarding function we use std::forward
, then and only then do we allow the demoting of types; because we are now at the point where it matters most.
If you need to, read more on universal references and perfect forwarding; Scott Meyers is pretty great as a resource.
Args
was empty? – Jerryjerrybuild