--- title: "Variadic templates in C++" description: "Variadic templates in C++11: parameter packs, recursive expansion with a base case, C++17 fold expressions, and where they are used." date: 2023-04-06 last_modified_at: 2026-10-02 keywords: [C++, variadic templates, parameter pack, fold expressions, C++17] --- # Variadic Templates in C++ Variadic templates, introduced in C++11, allow you to define templates that accept an arbitrary number of arguments of any type. ## Basic Syntax ```cpp template return_type function_name(Args... args); ``` The ellipsis (`...`) indicates a parameter pack, which can contain zero or more template arguments. ## Recursive Implementation Example A common pattern is to use recursion to process variadic templates: ```cpp // Base case to terminate recursion void print() { std::cout << std::endl; } // Recursive case template void print(T first, Args... rest) { std::cout << first << " "; print(rest...); // Recursive call with remaining arguments } // Usage print(1, 2.5, "hello", 'c'); // Outputs: 1 2.5 hello c ``` ## Fold Expressions (C++17) C++17 introduced fold expressions to simplify variadic template code: ```cpp template auto sum(Args... args) { return (... + args); // Unary left fold } // Usage int total = sum(1, 2, 3, 4, 5); // 15 ``` ## Applications Variadic templates are particularly useful for: - Creating type-safe variadic functions - Implementing perfect forwarding - Building tuple-like data structures - Creating compile-time type lists