Variadic templates
A variadic template accepts any number of template arguments, each with its own type. The group is called a parameter pack, and the compiler expands it into real arguments when the template is instantiated.
Detailed Explanation
C solved "any number of arguments" with ... and va_arg. That mechanism has no type information at all. printf("%d", 3.5) compiles and then reads the wrong bytes, which is undefined behavior; compilers only catch it because they special-case the format string. You also cannot pass a non-trivial class type through C varargs safely. Variadic templates, added in C++11, give you the same flexibility with full type checking and no runtime cost.
The declaration is template <typename... Ts>, and a function takes them as Ts... args. Ts is a template parameter pack, a list of types. args is a function parameter pack, a list of values. Neither is a container you can index; a pack only exists as something you expand.
Three pieces of syntax do all the work. sizeof...(Ts) gives the number of elements as a compile-time constant. The trailing ... after a pattern is pack expansion: writing f(args)... produces f(a0), f(a1), f(a2). The pattern can be as complicated as you like, and the ... repeats the whole thing. And Ts&&... args in a deduced context is a forwarding reference pack, which is what lets you pass arguments through untouched.
Before C++17 the only way to process a pack was recursive expansion: write an overload that peels off the first argument and calls itself with the rest, plus a base case for the empty pack. It works and you will see it in older code, but each step instantiates another function, so compile time and error messages both suffer.
C++17 added fold expressions, which collapse a pack over a binary operator in one step. (... + values) is a left fold that sums the pack. (std::cout << ... << args) prints each one. (... && predicates) short-circuits. The comma operator gives you a general "do this for each element" loop: ((std::cout << args << ' '), ...). Folds are shorter, compile faster, and produce errors you can read.
Perfect forwarding is the pack's most common industrial use. When you write a wrapper that must pass arguments to a constructor without deciding for the caller whether they are lvalues or rvalues, you take Args&&... args and expand std::forward<Args>(args).... Each element keeps its own value category, so an rvalue stays movable and an lvalue stays a copy. Note the placement: std::forward<Args>(args)... expands the whole call, once per element.
That single line is why std::make_unique<T>(args...), std::make_shared, and vector::emplace_back exist. emplace_back forwards your arguments straight into a constructor call inside the vector's storage, so the element is built in place instead of being constructed elsewhere and then moved or copied. For a std::vector<std::string>, push_back(std::string(50, 'x')) constructs then moves; emplace_back(50, 'x') constructs once.
The other classic use is a type-safe replacement for printf, where each argument is streamed with the operator its own type provides, so a type mismatch is a compile error rather than corrupted output. C++20's std::format is that idea finished.
Code Examples
#include <iostream>
// C++17 fold expressions: no recursion, no base case.
template <typename... Ts>
auto sum(Ts... values) {
return (... + values); // left fold: ((v0 + v1) + v2) ...
}
template <typename... Ts>
void printAll(const Ts&... args) {
std::cout << "count=" << sizeof...(Ts) << ": ";
((std::cout << args << ' '), ...); // comma fold: one statement per element
std::cout << '\n';
}
int main() {
std::cout << sum(1, 2, 3, 4) << '\n'; // prints: 10
printAll(42, "hello", 3.5); // prints: count=3: 42 hello 3.5
}#include <memory>
#include <string>
#include <utility>
#include <vector>
// How make_unique works: forward every argument into T's constructor,
// preserving whether each one was an lvalue or an rvalue.
template <typename T, typename... Args>
std::unique_ptr<T> makeUnique(Args&&... args) {
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
struct User {
std::string name;
int id;
User(std::string n, int i) : name(std::move(n)), id(i) {}
};
int main() {
std::string owned = "ada";
auto a = makeUnique<User>(owned, 1); // owned is copied
auto b = makeUnique<User>(std::move(owned), 2); // moved, no allocation
std::vector<User> users;
users.emplace_back("grace", 3); // constructs in place, no temporary User
}Common Gotchas
Expansion position changes the meaning
`f(std::forward<Args>(args))...` expands each call separately, while `f(std::forward<Args>(args)...)` makes one call with all arguments. Both compile in some contexts and do different things.
Empty packs need thought
a fold over `+` or `*` on an empty pack is ill-formed unless you write a binary fold with an initial value, such as `(0 + ... + values)`. Recursive versions need an explicit base-case overload.
A variadic constructor is a greedy overload
`template <typename... Args> Widget(Args&&...)` can beat the copy constructor when called with a non-const `Widget&`. Constrain it with a C++20 concept or `enable_if` so it does not hijack copies.