Lesson 4 of 6
Variadic Templates & Perfect Forwarding Intro
**Variadic templates** (C++11) accept any number of type arguments using the **parameter pack** (`typename... Args`). They power `std::make_unique`, `std::make_shared`, `std::tuple`, `std::variant`, and `emplace_back`. **Perfect forwarding** with `std::forward<T>` preserves the value category (lvalue/rvalue) of function arguments when passing them through a template - enabling wrapper functions that correctly forward to constructors and other functions.
Variadic Templates, Fold Expressions & std::forward
#include <iostream>
#include <string>
#include <memory>
#include <tuple>
#include <utility>
// ── Variadic function template - sum all args ─────────────────
// Base case (C++11 style: recursive unpacking)
template<typename T>
T sum(T val) { return val; }
template<typename T, typename... Rest>
T sum(T first, Rest... rest) {
return first + sum(rest...); // recursive: unpacks one at a time
}
// ── C++17 fold expressions - cleaner ─────────────────────────
template<typename... T>
auto sum_fold(T... vals) {
return (... + vals); // unary left fold: ((val1 + val2) + val3) + ...
}
template<typename... T>
void print_all(T&&... args) {
((std::cout << args << " "), ...); // comma fold - prints all args
std::cout << "
";
}
// ── sizeof... - count arguments ───────────────────────────────
template<typename... T>
constexpr size_t arg_count(T...) { return sizeof...(T); }
// ── Perfect forwarding - preserves lvalue/rvalue ──────────────
// T&& in template context = "forwarding reference" (universal reference)
// NOT the same as rvalue reference in non-template context
template<typename T, typename... Args>
T* create(Args&&... args) {
// std::forward<Args>(args)... preserves value category:
// - If args[i] was passed as lvalue → forwards as lvalue (T&)
// - If args[i] was passed as rvalue → forwards as rvalue (T&&)
return new T(std::forward<Args>(args)...);
}
// ── emplace pattern - forward args to constructor ─────────────
class Widget {
std::string name_;
int id_;
double value_;
public:
Widget(std::string n, int id, double v)
: name_(std::move(n)), id_(id), value_(v)
{ std::cout << "Widget(" << name_ << "," << id_ << "," << value_ << ")
"; }
};
// ── std::tuple and structured bindings ───────────────────────
auto make_triple(int a, double b, std::string c) {
return std::make_tuple(a, b, std::move(c)); // variadic under the hood
}
int main() {
// Variadic sum
std::cout << sum(1, 2, 3, 4, 5) << "
"; // 15
std::cout << sum_fold(1, 2, 3, 4, 5) << "
"; // 15
std::cout << sum_fold(1.0, 2.5, 3.7) << "
"; // 7.2
// Print all
print_all(42, "hello", 3.14, true); // 42 hello 3.14 1
// sizeof...
std::cout << arg_count(1, "x", 3.0) << "
"; // 3
// Perfect forwarding factory
std::string name = "Button";
Widget* w1 = create<Widget>(name, 1, 1.5); // lvalue name - copied
Widget* w2 = create<Widget>(std::move(name), 2, 2.5); // rvalue - moved
delete w1; delete w2;
// std::tuple
auto t = make_triple(42, 3.14, "hello");
auto [x, y, z] = t; // C++17 structured bindings
std::cout << x << " " << y << " " << z << "
"; // 42 3.14 hello
return 0;
}Common Mistakes
- `T&&` is only a forwarding reference when `T` is a deduced template parameter - `void f(Widget&&)` is an rvalue reference (non-template). `template<T> void f(T&&)` is a forwarding reference. The distinction matters: std::forward is only correct with forwarding references.
- Missing `std::forward` breaks perfect forwarding - `T(args...)` without forward always treats `args` as lvalues inside the function (named variables are lvalues). You MUST use `std::forward<Args>(args)...` to preserve rvalue-ness.
- Fold expression associativity - `(... - vals)` is left fold: `((v1 - v2) - v3)`. `(vals - ...)` is right fold: `(v1 - (v2 - v3))`. These give different results for non-associative operations like subtraction and division.
Tip
Tip
Practice Variadic Templates Perfect Forwarding Intro in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Accepting variable parameter packs and expanding expressions cleanly
Practice Task
Note
Practice Task - (1) Write a working example of Variadic Templates Perfect Forwarding Intro from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Variadic Templates Perfect Forwarding Intro is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Key Takeaways
- **Variadic templates** (C++11) accept any number of type arguments using the **parameter pack** (`typename.
- `T&&` is only a forwarding reference when `T` is a deduced template parameter - `void f(Widget&&)` is an rvalue reference (non-template). `template<T> void f(T&&)` is a forwarding reference. The distinction matters: std::forward is only correct with forwarding references.
- Missing `std::forward` breaks perfect forwarding - `T(args...)` without forward always treats `args` as lvalues inside the function (named variables are lvalues). You MUST use `std::forward<Args>(args)...` to preserve rvalue-ness.
- Fold expression associativity - `(... - vals)` is left fold: `((v1 - v2) - v3)`. `(vals - ...)` is right fold: `(v1 - (v2 - v3))`. These give different results for non-associative operations like subtraction and division.
Finished this lesson?