Variadic templates
- C++ course
- Advanced
- Lesson 7/83
- 5 min
Learn variable number of types with variadic templates.
Variadic template
A variadic template takes zero or more type parameters. The syntax is template <typename... Args>. The ellipsis (...) marks a parameter pack and lets Args hold any number of types.
This is the foundation of standard tools like std::make_shared, std::tuple and std::function. A single template handles both foo() and foo(int, double, std::string). The pack is expanded at compile time with no run-time cost.
Pack size
To learn how many elements a parameter pack holds, use sizeof...(Args). The result is a compile-time constant. Example: sizeof...(Args) returns 3 for Args = {int, double, char}.
This count can drive compile-time branches. For example, when the pack is empty sizeof...(Args) == 0 runs different code. The pack size is fixed by the type list the template is called with; the user does not count it manually.
Practice Write the Count template
Write template <typename... Args> struct Count with static const int value = sizeof...(Args); inside. In main write std::cout << Count<int, double, char>::value;.
Starter code
#include <iostream>
// Write the Count template: takes typename... Args
int main() {
// Print the result
return 0;
}Sample solution
#include <iostream>
template <typename... Args>
struct Count {
static const int value = sizeof...(Args);
};
int main() {
std::cout << Count<int, double, char>::value;
return 0;
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which line is a variadic template?
- template <int N>
- template <typename T>
- template <typename... Args> Correct answer
- template <>
Explanation: typename... Args takes zero or more types.
2 Complete the pack size
template <typename... Args>
struct Count {
static const int value = ____;
};
template <typename... Args>
struct Count {
static const int value = sizeof...(Args);
};
Explanation: sizeof...(Args) gives the pack size.
3 Match each piece to its role
| Term | Meaning |
|---|---|
typename... Args |
Type parameter pack |
sizeof...(Args) |
Pack size |
template <typename... Args> |
Variadic template |
Args... args |
Value parameter pack |