Writing a function template with a variable number of arguments
It is sometimes useful to write functions with a variable number of arguments or classes with a variable number of members. Typical examples include functions such as printf
that take a format and a variable number of arguments, or classes such as tuple
. Before C++11, the former was possible only with the use of variadic macros (that enable writing only type-unsafe functions) and the latter was not possible at all. C++11 introduced variadic templates, which are templates with a variable number of arguments that make it possible to write both type-safe function templates with a variable number of arguments and also class templates with a variable number of members. In this recipe, we will look at writing function templates.
Getting ready
Functions with a variable number of arguments are called variadic functions. Function templates with a variable number of arguments are called variadic function templates. Knowledge of C++ variadic...