Skip to content
AgileLogics
5 min read

Variadic Templates

Prerequisites: Modern C++ standards: C++11 through C++23

A variadic template accepts any number of arguments of any types, resolved entirely at compile time — the mechanism behind std::make_unique, std::vector's emplace_back, and similar standard library functions.

template<typename T>
T sum(T last) {
    return last;
}

template<typename T, typename... Rest>
T sum(T first, Rest... rest) {
    return first + sum(rest...);
}

std::cout << sum(1, 2, 3, 4) << std::endl; // 10

Rest... rest is a parameter pack — it expands recursively, one argument peeled off per call, until only one argument remains and the first overload matches.