In order to write variadic function templates, you must perform the following steps:
- Define an overload with a fixed number of arguments to end compile-time recursion if the semantics of the variadic function template require it (refer to [1] in the following code).
- Define a template parameter pack to introduce a template parameter that can hold any number of arguments, including zero; these arguments can be either types, non-types, or templates (refer to [2]).
- Define a function parameter pack to hold any number of function arguments, including zero; the size of the template parameter pack and the corresponding function parameter pack is the same and can be determined with the sizeof... operator (refer to [3]).
- Expand the parameter pack in order to replace it with the actual arguments being supplied (refer to [4]).
The following example that illustrates all the preceding points, is a variadic function template that adds a variable number of arguments using operator+:
template <typename T> // [1] overload with fixed
T add(T value) // number of arguments
{
return value;
}
template <typename T, typename... Ts> // [2] typename... Ts
T add(T head, Ts... rest) // [3] Ts... rest
{
return head + add(rest...); // [4] rest...
}