What is Variadic Templates and Parameter Packs?
Why Interviewers Ask This
Senior C++ engineers are expected to reason about architecture, performance, and edge cases. This question separates mid-level from senior candidates by testing deep system-level understanding.
Answer
Variadic templates (C++11) allow templates to accept any number of type parameters — enabling type-safe, compile-time generic code for variable-argument functions. Basic variadic function: // Base case (empty pack): void print() {} // Recursive case: template<typename T, typename... Rest> void print(T first, Rest... rest) { std::cout << first << " "; print(rest...); // Recursive call with remaining args } print(1, "hello", 3.14, true); // 1 hello 3.14 1. Fold expressions (C++17) — much simpler: template<typename... Args> auto sum(Args... args) { return (args + ...); // Unary right fold } template<typename... Args> void printAll(Args&&... args) { (std::cout << ... << args) << "\n"; // Binary left fold } template<typename... Args> bool allTrue(Args... args) { return (... && args); // All must be true } sum(1, 2, 3, 4); // 10 printAll("Hello ", "World ", 42); // Hello World 42 allTrue(true, true, false); // false. sizeof... operator: count parameters: template<typename... Args> constexpr size_t argCount(Args...) { return sizeof...(Args); } argCount(1, "hi", 3.14); // 3. Perfect forwarding with variadic: template<typename T, typename... Args> std::unique_ptr<T> make_unique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); }. std::tuple internals: variadic template: template<typename... Ts> class tuple; auto t = std::make_tuple(1, "hello", 3.14); std::get<0>(t); // 1 std::get<1>(t); // "hello". Index sequences: template<size_t... Is> void process(std::index_sequence<Is...>) { ((std::cout << Is), ...); // 0 1 2 3 } process(std::make_index_sequence<4>{});
Common Mistake
Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex C++ answers easy to follow.