Learning Hub Search Ctrl K

Modern C++ › C++11

Variadic Templates

Parameter packs and perfect forwarding.

Since C++11 advanced #variadic-templates#parameter-pack#perfect-forwarding#std-forward#sizeof...

Explanation

A variadic template accepts any number of template arguments through a parameter pack:

template <typename... Ts>       // Ts is a pack of types
void f(Ts... args);             // args is a pack of values

You process a pack by expansion: args... expands to the comma-separated elements, and a pattern like g(args)... applies g to each. The classic technique is recursion: handle the first argument, then recurse on the rest (with a base case). sizeof...(args) gives the number of elements. C++17 fold expressions simplify most of this.

Perfect forwarding passes arguments on while keeping their value category (lvalue/rvalue): take T&& (a forwarding reference in a deduced context) and call std::forward<T>(arg). It is how std::make_unique, emplace_back and std::thread pass constructor arguments through without extra copies.

Example

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

// recursion: base case + recursive case
void print() { std::cout << "\n"; }

template <typename T, typename... Rest>
void print(const T& first, const Rest&... rest) {
    std::cout << first;
    if (sizeof...(rest) > 0) std::cout << ", ";
    print(rest...);                                   // expand the remaining pack
}

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

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

// perfect forwarding: a make_unique clone
template <typename T, typename... Args>
std::unique_ptr<T> myMakeUnique(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

struct Person {
    std::string name; int age;
    Person(std::string n, int a) : name(std::move(n)), age(a) {}
};

int main() {
    print(1, "two", 3.5, 'c');                        // 1, two, 3.5, c
    std::cout << sum(1, 2, 3, 4) << " " << sum(1.5, 2.5) << "\n";   // 10 4

    auto p = myMakeUnique<Person>("Ann", 30);         // no extra copies of the string
    std::cout << p->name << " " << p->age << "\n";
    return 0;
}

Common pitfalls

  • Forgetting the base case produces a cryptic “no matching function” error at the end of the recursion.
  • T&& is a forwarding reference only when T is deduced for that function; std::vector<T>&& is a plain rvalue reference.
  • Forwarding must use std::forward<T>(x): using std::move on a forwarded argument breaks lvalue arguments.
  • A forwarded name is an lvalue inside the function; forward it once, don’t use it afterward.
  • Heavy recursion over big packs slows compilation; prefer fold expressions in C++17.

Legacy vs modern

C++98 simulated variadic templates with C varargs (va_list, not type safe) or with overload sets for 1..N arguments (Boost used preprocessor tricks). C++17 adds fold expressions ((args + ...)), and C++20 concepts constrain packs. See CTAD, Fold Expressions and Inline Variables.

Exercises

1. What does sizeof...(Ts) return for f<int, double, char>()?

3: the number of elements in the pack.