Skip to content

Variadic Templates

Variadic templates allow you to write functions and classes that can accept any number of arguments of any type.

The Problem: Fixed Number of Arguments

Before C++11, you had to write multiple overloads for different numbers of arguments:

cpp
// Old way - multiple overloads needed
int sum(int a) { return a; }
int sum(int a, int b) { return a + b; }
int sum(int a, int b, int c) { return a + b + c; }
// ... and so on for every possible number of arguments

There was an alternative way to do this using VA_ARGS macro, but it was not type-safe and required manual argument counting.

The Solution: Variadic Templates

Variadic templates use the ... syntax to accept any number of arguments:

cpp
// Base case - one argument
template<typename T>
T sum(T first) { return first; }

// Variadic case - multiple arguments
template<typename T, typename... Args>
T sum(T first, Args... args) {
    return first + sum(args...);
}

Fold Expressions

Fold expressions are required to unpack the parameter pack created while using variadic templates.

By default, args... will be expanded as a comma-separated list of arguments. But you can use the ... operator with operators to perform operations on the arguments without the need of recursion.

Unary Folds

cpp
// Check if all arguments are true
template<typename... Args>
bool all_true(Args... args) {
    return (... && args);
}

// Check if any argument is true
template<typename... Args>
bool any_true(Args... args) {
    return (... || args);
}

Binary Folds

cpp
// Left fold: ((a + b) + c) + d
template<typename... Args>
auto sum_left(Args... args) {
    return (... + args);
}

// Right fold: a + (b + (c + d))
template<typename... Args>
auto sum_right(Args... args) {
    return (args + ...);
}

Implement a variadic template function called 'count_true' that counts how many of the provided boolean arguments are true. The function should work with any number of boolean arguments and return the count of true values.

cpp
// TODO: Implement a variadic template function called count_true
// that counts how many boolean arguments are true.
// The function should work with any number of boolean arguments.
// Example usage: count_true(true, false, true) should return 2

// Your implementation here