Jaskamal Kainth

Variadic Templates in C++

Variadic templates, introduced in C++11, allow you to define templates that accept an arbitrary number of arguments of any type.

Basic Syntax

template<typename... Args>
return_type function_name(Args... args);

The ellipsis (...) indicates a parameter pack, which can contain zero or more template arguments.

Recursive Implementation Example

A common pattern is to use recursion to process variadic templates:

// Base case to terminate recursion
void print() {
    std::cout << std::endl;
}

// Recursive case
template<typename T, typename... Args>
void print(T first, Args... rest) {
    std::cout << first << " ";
    print(rest...); // Recursive call with remaining arguments
}

// Usage
print(1, 2.5, "hello", 'c'); // Outputs: 1 2.5 hello c

Fold Expressions (C++17)

C++17 introduced fold expressions to simplify variadic template code:

template<typename... Args>
auto sum(Args... args) {
    return (... + args); // Unary left fold
}

// Usage
int total = sum(1, 2, 3, 4, 5); // 15

Applications

Variadic templates are particularly useful for: