C++ · Module 12 · Lesson 41 min read

Variadic Templates & Fold Expressions

Parameter packs

arduino
template <typename... Args>
void log(const Args&... args);   // zero or more arguments of any types
  • typename... Args — a template parameter pack
  • const Args&... args — a function parameter pack
  • sizeof...(args) — how many there are

Fold expressions (C++17) ✅

Apply an operator across all arguments:

arduino
template <typename... T>
auto sum(T... xs) { return (xs + ...); }          // x1 + (x2 + (x3 + ...))

template <typename... T>
void print(const T&... xs) { ((std::cout << xs << ' '), ...); }   // comma fold
FormExpands to
(pack op ...)right fold: a op (b op c)
(... op pack)left fold: (a op b) op c
(pack op ... op init)with an initial value (safe for empty packs)

&&, || and , folds work with empty packs (true, false, void).

Pre-C++17: recursion

arduino
void print() {}                                          // base case
template <typename T, typename... Rest>
void print(const T& first, const Rest&... rest) { std::cout << first; print(rest...); }

Perfect forwarding of packs

arduino
template <typename T, typename... Args>
std::unique_ptr<T> my_make_unique(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

This is essentially how make_unique, emplace_back and std::thread's constructor work.

Pack expansion

f(args)... applies the pattern to each element: f(a1), f(a2), f(a3).

Variadic class templates

std::tuple<int, std::string, double> and std::variant<...> are built on parameter packs.

Example

C++
#include <iostream>
#include <memory>
#include <string>
#include <utility>

template <typename... T>
auto sum(T... xs) { return (xs + ... + 0); }              // fold with initial value: works for zero args

template <typename... T>
void print_line(const T&... xs) {
    ((std::cout << xs << ' '), ...);                       // comma fold
    std::cout << '\n';
}

template <typename... T>
bool all_positive(T... xs) { return ((xs > 0) && ...); }   // && fold (true for empty pack)

template <typename... T>
std::size_t count_args(const T&...) { return sizeof...(T); }

// Pre-C++17 style: recursion with a base case
void join(std::string&) {}
template <typename First, typename... Rest>
void join(std::string& out, const First& first, const Rest&... rest) {
    out += first;
    if constexpr (sizeof...(rest) > 0) out += ", ";
    join(out, rest...);
}

// Perfect forwarding of a pack (how make_unique works)
template <typename T, typename... Args>
std::unique_ptr<T> create(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

struct Expense {
    std::string category;
    double amount;
    std::string note;
    Expense(std::string c, double a, std::string n) : category(std::move(c)), amount(a), note(std::move(n)) {}
};

int main() {
    std::cout << "sum(1, 2, 3, 4) = " << sum(1, 2, 3, 4) << '\n';
    std::cout << "sum(1.5, 2.5) = " << sum(1.5, 2.5) << ", sum() = " << sum() << '\n';
    print_line("Rent", 15000, "paid:", true);
    std::cout << std::boolalpha << "all_positive(3, 5, 9) = " << all_positive(3, 5, 9)
              << ", all_positive(3, -1) = " << all_positive(3, -1) << '\n';
    std::cout << "count_args('a', 2, \"three\", 4.0) = " << count_args('a', 2, "three", 4.0) << '\n';

    std::string list;
    join(list, std::string("Food"), "Rent", "Travel");
    std::cout << "joined: " << list << '\n';

    auto e = create<Expense>("Food", 450.0, "momo lunch");
    std::cout << "created: " << e->category << ' ' << e->amount << " (" << e->note << ")\n";
    return 0;
}

/* Output:
sum(1, 2, 3, 4) = 10
sum(1.5, 2.5) = 4, sum() = 0
Rent 15000 paid: 1
all_positive(3, 5, 9) = true, all_positive(3, -1) = false
count_args('a', 2, "three", 4.0) = 4
joined: Food, Rent, Travel
created: Food 450 (momo lunch)
*/