参数包
来自cppreference.com
参数包是对变长模板参数以及展开到变长模板参数的变长函数参数的称呼。
目录 |
[编辑] 语法
class ... identifier
|
(1) | (since C++11) | |||||||
identifier ... name
|
(2) | (since C++11) | |||||||
name ...
|
(3) | (since C++11) | |||||||
[编辑] 释义
1) 模板参数包声明。
模板的参数表包含一个可接受任意数量实参的参数。
2) 函数参数包声明。
函数的参数表包含一个可接受任意数量实参的参数。
3) 函数参数包展开式。
在函数体中展开为函数参数包的实参。
本章尚未完成 |
[编辑] 举例
#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
此例定义了一个类似于 std::printf 的函数,它将格式串中出现的每个字符%都替换为一个值。
如果只传递了格式串,那么会调用第一个重载形式,不存在参数展开的情况。
第二个重载形式包含一个单独的模板参数作为参数的开头,还包含一个参数包。我们可以递归调用本函数然后只传递参数包尾部的那个参数,直到参数包为空。
Targs
是模板参数包, Fargs
是函数参数包
[编辑] 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 |