Get the App
SLTechnology News&Howtos  ›  Development  › 

What is the deployment method of C++ variable parameter template?

Shulou Source: shulou.com Published: 2022-06-01 01:11:55 10月03日 Update

This article mainly explains the "C++ variable parameter template deployment way is what", the article explains the content is simple and clear, easy to learn and understand, now please follow the editor's ideas slowly in depth, together to study and learn "C++ variable parameter template is what is the way to expand it!"

Variable parameter template (variadic templates) is one of the new powerful features of Category 11. It highly generalizes the template parameters and can represent 0 to any number of parameters of any type. Compared with the "antiquities" of these templates and function templates, which can only contain a fixed number of template parameters, variable template parameters are undoubtedly a great improvement.

If you are new to the variable parameter template, you may feel more abstract and not easy to use. The expansion of the template parameters is usually necessary when using the variable parameter template, so this article enumerates some common template deployment methods to help us have a preliminary understanding of the variable parameter template.

Definition of variable parameter template

The definition of a variable parameter template is similar to that of a normal template, which needs to be written with an ellipsis after typename or class. Here is a common variable parameter function template:

Template void func (T... Args) {/.}

The above function template parameter args is preceded by an ellipsis, so it is a variable template parameter called template parameter package (template parameter pack), which contains 0 to N template parameters, and we cannot directly obtain every parameter in args, we can only obtain each parameter in the parameter package by expanding the parameter package, which is also the focus of this article.

Expansion of parameter package

The way of parameter package deployment is keeping pace with the development of C++ language. We take the implementation of a variable parameter format print function as an example to list some common ways:

Recursive function expansion

# include void FormatPrint () {std::cout FormatPrint (), the output is as follows:

> albert@home-pc:/mnt/d/data/cpp/testtemplate$ good + testtemplate.cpp-- std=c++11albert@home-pc:/mnt/d/data/cpp/testtemplate$. / a.out [1] [2] [3] [4] [good] [2] [hello] [4] [110]

Comma expression expansion

# include template void FormatPrint (Args... Args) {(void) std::initializer_list {(std::cout)

Tags: Parameter template variable way expression function content Recursion that is template format clocked output number Code Type comma selection property Index Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Shulou Technology Xiaomi macOS MySQL