Understanding variadic templates
In the previous section, we learned how to write function or class templates with a fixed number of type parameters. But since C++11, standard generic functions and class templates can accept a variable number of type parameters. This is called variadic templates, which is an extension of C++ (see the link in the Further reading section, context [6]. We will learn about the syntax and usage of variadic templates by looking at examples.
Syntax
If a function or class template takes zero or more parameters, it can be defined as follows:
//a class template with zero or more type parameterstemplate <typename... Args> class X { ... }; //a function template with zero or more type parameters template <typename... Args> void foo( function param list) { … }
Here, <typename ... Args>
declares a parameter pack. Note that here, Args
is not a keyword; you can use any valid variable name. The preceding class/function template can...