Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Variadic Templates | Template Specialization
C++ Templates
course content

Conteúdo do Curso

C++ Templates

C++ Templates

1. Creating First Template
2. Templates Usage
3. Template Specialization
4. Class
5. Template Metaprogramming

Variadic Templates

Variadic templates stand as a pinnacle of this flexibility, allowing you to define functions and classes that can accept a variable number of arguments. They empower C++ programmers to write concise and efficient code that adapts to diverse scenarios.

Syntax of Variadic Templates

Variadic templates leverage the power of template parameter packs. A template parameter pack allows you to accept an arbitrary number of template arguments. The syntax for declaring a template parameter pack involves using an ellipsis (...) after the type or template parameter.

h

Example

copy
12345
template<typename... Args> void printArgs(Args... args) { // Print all arguments (std::cout << ... << args) << '\n'; }

In this example, Args is a template parameter pack that can accept zero or more template arguments. Inside the function printArgs, the ellipsis (...) expands the pack, allowing you to access each individual argument.

Using Variadic Templates

Variadic templates are incredibly versatile and can be used in a variety of contexts. Some common use cases include:

  • Logging and Debugging: You can create logging functions that accept a variable number of arguments to simplify debug output.
  • Recursive Algorithms: Variadic templates are frequently employed in recursive algorithms where the number of arguments may vary.
  • Container Classes: You can design container classes, such as tuples or variant types, using variadic templates to store heterogeneous data.
  • Wrapper Functions: Variadic templates are useful for creating wrapper functions that forward arguments to other functions with different signatures.
cpp

main

copy
123456789101112131415161718
#include <iostream> // Base case for recursion void print() { std::cout << std::endl; } // Recursive variadic template function template<typename T, typename... Args> void print(T first, Args... args) { std::cout << first << ' '; print(args...); // Recursive call } int main() { print(1, 2.5, "Hello", 'c'); }

In this example, the print function takes a variable number of arguments and recursively prints them until there are no more arguments left.

Tudo estava claro?

Seção 3. Capítulo 3
We're sorry to hear that something went wrong. What happened?
some-alt