Variadic Templates in C++

Level 5437 keystrokes

A variadic template print() takes any number of arguments and prints them by recursion, ending with the one-argument version. sum() adds its arguments with a fold expression, which works for ints and for strings (concatenation).

C++ code

// Base case: a single argument ends the recursion
1template<typename T>
2void print(const T& value) {
// Prints the last value and a newline
3 cout << value << endl;
4}
5
// Args... is a parameter pack: zero or more types
6template<typename T, typename... Args>
// Splits the arguments into the first one and the rest
7void print(const T& first, const Args&... rest) {
// Prints the first one followed by a space
8 cout << first << " ";
// Recursive call with the rest; rest... expands the pack
9 print(rest...);
10}
11
12template<typename... Args>
// auto deduces the return type from the expression
13auto sum(Args... args) {
// Fold expression (C++17): expands to args1 + (args2 + (...))
14 return (args + ...);
15}
16
// Prints "Hello 42 3.14 World"
17print("Hello", 42, 3.14, "World");
// 1 + 2 + 3 + 4 + 5: prints "Sum: 15"
18cout << "Sum: " << sum(1, 2, 3, 4, 5) << endl;
// + on strings concatenates: prints "Concat: abc"
19cout << "Concat: " << sum(string("a"), string("b"), string("c")) << endl;

Output

Hello 42 3.14 World
Sum: 15
Concat: abc
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 23
  • .× 19
  • "× 16
  • ,× 11
  • (× 11
  • )× 11
  • ;× 7
  • {× 3
  • }× 3
  • &× 3

More C++ examples at level 5

← C++ typing practice