Summary - Variadic templates
- C++ course
- Advanced
- Lesson 12/83
- 5 min
Combine fold expressions and perfect forwarding to write a print function.
Summary - Variadic templates
In this group you met five tools of variadic templates: type packs with typename... Args, value packs with Args... args, pack size with sizeof..., fold expressions with (args + ...) and heterogeneous packing with std::tuple. Perfect forwarding ties these tools together in wrapper functions.
Together they form the foundation of modern APIs like std::make_unique and std::emplace_back. Now you will write a small task that combines what you learned.
Practice Summary with tuple + fold
Write template <typename... Args> auto sum_all(Args... args) with body return (args + ...);. In main create auto t = std::make_tuple(1, 2, 3);, then call sum_all(std::get<0>(t), std::get<1>(t), std::get<2>(t)) and print the result via std::cout.
Starter code
#include <iostream>
#include <tuple>
// Write the sum_all template with a fold
int main() {
// Build a tuple, call sum_all and print
return 0;
}Sample solution
#include <iostream>
#include <tuple>
template <typename... Args>
auto sum_all(Args... args) {
return (args + ...);
}
int main() {
auto t = std::make_tuple(1, 2, 3);
std::cout << sum_all(std::get<0>(t), std::get<1>(t), std::get<2>(t));
return 0;
}Expected output
6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which tool reduces a pack with one operator?
- sizeof...
- std::forward
- std::tuple
- fold expression Correct answer
Explanation: A fold expression (args + ...) reduces a pack with one operator.
2 Match each tool to its purpose
| Term | Meaning |
|---|---|
typename... Args |
Type pack definition |
sizeof...(Args) |
Pack size |
(args + ...) |
Fold reduction |
std::tuple<T1, T2> |
Heterogeneous pack |
3 Complete the fold line
template <typename... Args>
auto sum_all(Args... args) {
return (args + ____);
}
template <typename... Args>
auto sum_all(Args... args) {
return (args + ...);
}
Explanation: (args + ...) is a right fold.