Parameter pack

来自cppreference.com
< cpp‎ | language
 
 
C++语言
表达式
替代表示
字面量
布尔型 - 整型 - 浮点型
字符型 - 字符串 - nullptr (C++11)
用户定义 (C++11)
Utilities
属性 (C++11)
Types
typedef声明
类型别名声明 (C++11)
Casts
隐式类型转换 - 显示类型转换
static_cast - dynamic_cast
const_cast - reinterpret_cast
内存分配
类特有的函数属性
explicit (C++11)
static
静态成员函数
模板
模板特化
参数包 (C++11)
杂项
 

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