Parameter pack
- C++ course
- Advanced
- Lesson 8/83
- 5 min
Learn parameter pack and expansion.
Parameter pack
A parameter pack holds zero or more values under a single name. A type pack is written typename... Args and a value pack Args... args. The pack is expanded at compile time; separate code is generated for each element.
Example: template <typename... Args> void f(Args... args) takes any number of arguments. The call f(1, 2.0, 'x') produces Args = {int, double, char} and args = {1, 2.0, 'x'}. The pack is expanded inside the function body.
Pack expansion
A pack is expanded automatically when used in a function body. sizeof...(args) gives the number of values. To process pack elements one by one, use a fold expression or a recursive template.
Recursive approach: a function takes the first argument and passes the rest to itself. An overload for the empty pack acts as the base case. This classic technique was common before C++17; fold expressions now offer a shorter form.
Practice count_args function
Write template <typename... Args> int count_args(Args... args). The body should be return sizeof...(Args);. In main call count_args(1, 2.0, "x") and print the result via std::cout.
Starter code
#include <iostream>
// Write the count_args template
int main() {
// Call count_args(1, 2.0, "x") and print
return 0;
}Sample solution
#include <iostream>
template <typename... Args>
int count_args(Args... args) {
return sizeof...(Args);
}
int main() {
std::cout << count_args(1, 2.0, "x");
return 0;
}Expected output
3
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the value pack
template <typename... Args>
void f(____) { }
template <typename... Args>
void f(Args... args) { }
Explanation: Args... args marks a value pack.
2 What does sizeof...(args) return?
template <typename... Args>
void f(Args... args) { return sizeof...(args); }- The number of values in the pack Correct answer
- The first type of the pack
- Byte count, not type count
- The address of the first value
Explanation: sizeof...(args) gives the number of values in the pack.
3 Match each expression to its purpose
| Term | Meaning |
|---|---|
typename... Args |
Type pack definition |
Args... args |
Value pack definition |
sizeof...(args) |
Value count |
sizeof...(Args) |
Type count |