Parameter pack
来自cppreference.com
A parameter pack is the name used to refer to the variadic template parameter and the function parameters expanding to that template parameter.
目录 |
[编辑] Syntax
class ... identifier
|
(1) | (C++11 起) | |||||||
identifier ... name
|
(2) | (C++11 起) | |||||||
name ...
|
(3) | (C++11 起) | |||||||
[编辑] Explanation
1) Template parameter pack declaration.
Inside a template parameter list, defines a parameter that can take any number of arguments.
2) Function parameter pack declaration.
Inside a function parameter list, defines a parameter that can take any number of arguments.
3) Function parameter pack expansion.
Inside a function body, expands to the arguments passed to the function parameter pack.
本章尚未完成 |
[编辑] 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; }
输出:
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
[编辑] 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 |