Variadic Templates
Templates with variable arguments
Interview Relevant: Modern C++
Variadic Templates
Templates that accept any number of arguments.
Code Examples
Variadic templates for flexible interfaces.
cpp
1// Variadic function template
2template<typename... Args>
3void print(Args... args) {
4 (cout << ... << args) << endl; // Fold expression (C++17)
5}
6print(1, 2.5, "hello"); // 12.5hello
7
8// Recursive approach (pre-C++17)
9template<typename T>
10void printRecursive(T value) {
11 cout << value << endl; // Base case
12}
13template<typename T, typename... Args>
14void printRecursive(T first, Args... rest) {
15 cout << first << " ";
16 printRecursive(rest...); // Recursive call
17}
18
19// sizeof... operator
20template<typename... Args>
21void countArgs(Args... args) {
22 cout << "Count: " << sizeof...(args) << endl;
23}
24
25// Perfect forwarding with variadic
26template<typename T, typename... Args>
27unique_ptr<T> make_unique(Args&&... args) {
28 return unique_ptr<T>(new T(forward<Args>(args)...));
29}