Parameter pack
A template parameter pack is a template parameter that accepts zero or more template arguments (non-types, types, or templates). A function parameter pack is a function parameter that accepts zero or more function arguments.
A template with at least one parameter pack is called a variadic template.
Contents |
[edit] Syntax
Template parameter pack (appears in a class template and in a function template parameter list)
type ... Args
|
(1) | (since C++11) | |||||||
typename|class ... Args
|
(2) | (since C++11) | |||||||
template < parameter-list > ... Args
|
(3) | (since C++11) | |||||||
Function parameter pack (appears in a function parameter list)
Args ... args
|
(4) | (since C++11) | |||||||
Parameter pack expansion (appears in a body of a variadic function template)
pattern ...
|
(5) | (since C++11) | |||||||
[edit] Explanation
pattern
s. Pattern must include at least one parameter pack.This section is incomplete Reason: list contexts where pack expansions occur (with examples) |
[edit] Example
#include <iostream> void tprintf(const char* format) // base function { std::cout << format; } template<typename T, typename... Targs> void tprintf(const char* format, T value, Targs... Fargs) // recursive variadic function { for ( ; *format != '\0'; format++ ) { if ( *format == '%' ) { std::cout << value; tprintf(format+1, Fargs...); // recursive call return; } std::cout << *format; } } int main() { tprintf("% world% %\n","Hello",'!',123); return 0; }
Output:
Hello world! 123
The above example defines a function similar to std::printf, that replace each occurrence of the character % in the format string with a value.
The first overload is called when only the format string is passed and there is no parameter expansion.
The second overload contains a separate template parameter for the head of the arguments and a parameter pack, this allows the recursive call to pass only the tail of the parameters until it becomes empty.
Targs
is the template parameter pack and Fargs
is the function parameter pack
[edit] See also
function template | |
class template | |
sizeof... | Queries the number of elements in a parameter pack. |
C-style variadic functions | |
Preprocessor macros | Can be variadic as well |