Fold Expressions in C++

Level 5477 keystrokes

C++17 fold expressions apply an operator to every element of a parameter pack: && checks that all arguments are true, || that at least one is, and a comma fold prints each argument. Booleans print as 1 or 0.

C++ code

1template<typename... Args>
2bool allTrue(Args... args) {
// Expands to args1 && args2 && ...: true only if all are true
3 return (args && ...);
4}
5
6template<typename... Args>
7bool anyTrue(Args... args) {
// Expands with ||: true if at least one is true
8 return (args || ...);
9}
10
11template<typename... Args>
12void printAll(Args... args) {
// Comma fold: runs cout << arg << " " for each argument, left to right
13 ((cout << args << " "), ...);
14 cout << endl;
15}
16
// All are true: prints "All true: 1"
17cout << "All true: " << allTrue(true, true, true) << endl;
// One is false: prints "All true: 0"
18cout << "All true: " << allTrue(true, false, true) << endl;
// One is true: prints "Any true: 1"
19cout << "Any true: " << anyTrue(false, true, false) << endl;
// Mixed types work too: prints "1 2.5 hello x"
20printAll(1, 2.5, "hello", 'x');

Output

All true: 1
All true: 0
Any true: 1
1 2.5 hello x
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.

  • .× 28
  • <× 27
  • (× 11
  • )× 11
  • ,× 10
  • "× 10
  • ;× 8
  • :× 3
  • {× 3
  • }× 3

More C++ examples at level 5

← C++ typing practice