How to Use Function Template Parameter Packs in C++
Method 1 of 2:
Using Non-Type Function-Template Parameter Packs
- Set up the main function. No header files are required to construct a variadic template. For demonstration purposes in this article, the iostream header file will be included.
#include using namespace std; int main() { }
- Construct a non-type templated function. The code below shows a function accepting an int template argument.
#include using namespace std; template<int N> void addOne() { cout << N+1 << endl; } int main() { addOne<5>(); // Expected output: 6 }
- Expand the template to a parameter pack. Consider what happens if you want to add more arguments to the function, so that you can call the function with any number of arguments. You could provide default arguments, e.g.
template<int N, int N2 = 0, int N3 = 0> void addOne() { cout << N+1 << " " << N2+1 << " " << N3+1 << endl; }
- But this is tedious. What's more, this will always output 3 numbers, regardless of the arguments passed. A parameter pack easily resolves this:
template<int ...Ns> void addOne() { for (int i : {Ns...}) cout << i+1 << endl; }
- The ellipsis "packs" int values into Ns. It is then "unpacked" into an initialiser-list in a for-range loop. The loop will output each value plus one as it iterates.
- You can use Ns to denote the presence multiple N template parameters.
- Call the function. Pass an arbitrary number of ints to the template and watch as you have successfully constructed and called your first variadic template function.
int main() { addOne<5, 1, 4, -20>(); // Expected Output: // 6 // 2 // 5 // -19 return 0; }
Method 2 of 2:
Using Type Function-Template Parameter Packs
- Set up up the main function and construct a simple templated function. Include any necessary header files. The template function used in this example will be a print function, output a variable of any type.
#include using namespace std; template<class T> void print(T arg) { cout << arg << endl; } int main() { print("Hello wikiHow!"); // Expected Output: // Hello wikiHow! }
- Due to type deduction, you don't need to pass any type-arguments to the template.
- Expand the template to a parameter pack. Similar to packing non-type template parameters, you use an ellipsis to pack types. The sample code below shows how function arguments can be white-space-delimited along a single line.
// parameter pack template<class T, class ...Ts> void print(T arg, Ts... args) { cout << " " << arg; print(args...); }
- It's impossible to unpack args into an initialiser-list unless the values passed into print all have the same type. However, you can rely on recursion to handle the job. One argument is deducted on each recursive iteration and printed.
- You can use Ts to denote multiple T. Note that these Ts could be of any type.
- You may also choose to unpack the values into an std::tuple.
- Provide a base case. Without the base case, compilers will throw errors about a missing print() function (with zero arguments). It is important to provide a base case to both terminate the recursion and handle any cleanup (in this case, printing a newline). When the number of arguments in print reaches 0, the base case will be called. A suitable base case that will terminate the recursion may be:
// base case void print() { cout << endl; }
- Test the function. Ensure that the function works correctly as intended.
int main() { print(2019, ':', "Happy", 14, "th", "Birthday", "wikiHow!"); // Expected Output: // 2019 : Happy 14 th Birthday wikiHow! }
- To use print on STL containers or user-defined classes, you will need to overload operator<<.
3.3 ★ | 3 Vote
You should read it
- PHP functions
- The best free Microsoft Word template download websites
- Lesson 25: Use the Template
- MS PowerPoint - Lesson 7: PowerPoint design template
- Invite download Profile template Curriculum vitae, job application, ... extremely professional from Microsoft
- Top gorgeous Word cover templates for books, reports, lesson plans
- Create slides from a template available in PowerPoint
- 13 beautiful event invitation card templates in Microsoft Word
May be interested
- How to Create a 20 Questions Game in C++this tutorial will walk you through creating 20 questions in c++ with numbers using visual studio. this tutorial is very 'bare bones' and only uses the basics of c++ programming. obtain a copy of visual studio and open it.
- How to Create a Recursive Function in C++recursion is a major topic in computer science. it is a method where a problem is reduced or simplified to smaller versions of itself until a solution is achieved. this tutorial will demonstrate how to write a simple recursive function in...
- How to Set Up OpenGL GLFW GLEW GLM on a Project with Visual Studiothis guide will help you get over the first challenge of using opengl, glfw, glew, and glm: installing and setting them up, and creating your first project with glfw-glew-glm template in visual studio 2019. it will assume your platform is...
- How to Use CMake to Get Binaries from Source Codecmake is useful in compiling source code for get binaries. compiling a library from the source code guarantees that the resulting library is perfectly tailored for your cpu/os, a luxury pre-compiled binaries don't always provide. it is...
- How to Quick Sort an Array in C++sorting is a very useful tool in programming. it is often necessary to arrange the members of a list in ascending or descending order. a sorted list allows a user to search and find information very quickly. sorting a list requires the...
- How to Program in C++ and Batchc++ is a mid-level programming language—it easy to write and it runs very quickly. as a result, it is widely used to develop games, business apps, and software, such as google chrome and microsoft office suite.https://www.youtube.com/wat...