As a starting point to see how parameter packs work, let’s consider a simple template function, one that displays a list consisting of just one item:
template<typename T>
void show_list0(T value)
{
std::cout << value << ", ";
}
This definition has two parameter lists. The template parameter list is just T
. The function parameter list is just value
. A function call such as the following sets T
in the template parameter list to double
and value
in the function parameter list to 2.15
:
show_list0(2.15);
C++11 provides an ellipsis meta-operator that enables you to declare an identifier for a template parameter pack, essentially a list of types. Similarly, it lets you declare an identifier for a function parameter pack, essentially a list of values. The syntax looks like this:
template<typename... Args> // Args is a template parameter pack
void show_list1(Args... args) // args is a function parameter pack
{
...
}
Args
is a template parameter pack, and args
is a function parameter pack. (As with other parameter names, any name satisfying C++ identifier rules can be used for these packs.) The difference between Args
and T
is that T
matches a single type, whereas Args
matches any number of types, including none. Consider the following function call:
show_list1('S', 80, "sweet", 4.5);
In this case the parameter pack Args
contains the types matching the parameters in the function call: char
, int
, const char *
, and double
.
Next, much as
void show_list0(T value)
states that value
is of type T
, the line
void show_list1(Args... args) // args is a function parameter pack
states that args
is of type Args
. More precisely, this means that the function pack args
contains a list of values that matches the list of types in the template pack Args
, both in type and in number. In this case, args
contains the values 'S'
, 80
, "sweet"
, and 4.5
.
In this manner, the show_list1()
variadic template can match any of the following function calls:
show_list1();
show_list1(99);
show_list1(88.5, "cat");
show_list1(2,4,6,8, "who do we", std::string("appreciate));
In the last case, the Args
template parameter pack would contain the types int
, int
, int
, int
, const char *
, and std::string
, and the args
function parameter pack would contain the matching values 2
, 4
, 6
, 8
, "who do we"
, and std::string("appreciate")
.
18.118.205.235