In computer programming, variadic templates are templates that take a variable number of arguments.
Variadic templates are supported by C++ (since the C++11 standard), and the D programming language.
The variadic template feature of C++ was designed by Douglas Gregor and Jaakko Järvi and was later standardized in C++11. Prior to C++11, templates (classes and functions) could only take a fixed number of arguments, which had to be specified when a template was first declared. C++11 allows template definitions to take an arbitrary number of arguments of any type.
The above template class tuple will take any number of typenames as its template parameters. Here, an instance of the above template class is instantiated with three type arguments:
The number of arguments can be zero, so tuple<> some_instance_name;
will work as well.
If one does not want to have a variadic template that takes 0 arguments, then this definition will work as well:
Variadic templates may also apply to functions, thus not only providing a type-safe add-on to variadic functions (such as printf) - but also allowing a printf-like function to process non-trivial objects.
The ellipsis (...) operator has two roles. When it occurs to the left of the name of a parameter, it declares a parameter pack. Using the parameter pack, the user can bind zero or more arguments to the variadic template parameters. Parameter packs can also be used for non-type parameters. By contrast, when the ellipsis operator occurs to the right of a template or function call argument, it unpacks the parameter packs into separate arguments, like the args...
in the body of printf
below. In practice, the use of an ellipsis operator in the code causes the whole expression that precedes the ellipsis to be repeated for every subsequent argument unpacked from the argument pack; and all these expressions will be separated by a comma.
The use of variadic templates is often recursive. The variadic parameters themselves are not readily available to the implementation of a function or class. Therefore, the typical mechanism for defining something like a C++11 variadic printf replacement would be as follows:
This is a recursive template. Notice that the variadic template version of printf calls itself, or (in the event that args... is empty) calls the base case.
There is no simple mechanism to iterate over the values of the variadic template. There are few ways to translate the argument pack into single argument use. Usually this will rely on function overloading, or - if the function can simply pick one argument at a time - using a dumb expansion marker: