LibraryFold Expressions

Fold Expressions

Learn about Fold Expressions as part of C++ Modern Systems Programming and Performance

C++ Fold Expressions: Simplifying Variadic Templates

Fold expressions, introduced in C++17, are a powerful feature for simplifying operations on parameter packs in variadic templates. They provide a concise syntax to apply an operation (like addition, multiplication, or a custom binary operation) across all elements of a parameter pack.

Understanding the Basics

A fold expression is essentially a shorthand for a recursive template expansion or a loop-like construct applied to a parameter pack. It consists of an operator and a parameter pack, with optional initial and final values.

Fold expressions reduce boilerplate code for variadic template operations.

Instead of writing explicit recursion or loops for parameter packs, fold expressions offer a single, elegant expression.

Consider a scenario where you want to sum all arguments passed to a function. Without fold expressions, you might use recursion. With fold expressions, this becomes a single line of code, significantly improving readability and maintainability.

Types of Fold Expressions

There are four primary forms of fold expressions:

FormSyntaxDescription
Unary Right FoldE op ...Expands to: ( ( (E1 op E2) op E3) op ... ) op En
Unary Left Fold... op EExpands to: E1 op ( E2 op ( ... op (En-1 op En) ) )
Binary Right Foldinit E op ...Expands to: ( init op E1) op E2) op ... ) op En
Binary Left Fold... op E initExpands to: E1 op ( E2 op ( ... op (En op init) ) )

Here,

code
E
represents the parameter pack,
code
op
is a binary operator (e.g.,
code
+
,
code
*
,
code
&&
,
code
||
,
code
,
,
code
->*
,
code
.
), and
code
init
is an optional initial value.

Practical Examples

Let's illustrate with common use cases.

What is the primary benefit of using fold expressions over traditional recursion for parameter pack operations?

Reduced boilerplate code, improved readability, and conciseness.

Summing Elements: A common use is summing all elements in a parameter pack.

Consider a function template sum that takes a parameter pack Args. A unary right fold expression (args + ...) can sum all elements. The expansion looks like ((arg1 + arg2) + arg3) + .... This elegantly handles any number of arguments without explicit recursive calls.

📚

Text-based content

Library pages focus on text content

Logical AND/OR: Fold expressions are also useful for logical operations.

Loading diagram...

For example,

code
(args && ...)
would evaluate to true only if all arguments are true. Similarly,
code
(args || ...)
would evaluate to true if at least one argument is true.

Advanced Usage and Considerations

Fold expressions can also use custom binary operations and the comma operator for sequencing.

The comma operator fold (std::cout << args << ' ')... is a common idiom for printing all elements of a parameter pack, separated by spaces.

When using binary folds, the

code
init
value plays a crucial role. For example, in a product fold
code
(1 * ... * args)
, the initial value of 1 ensures the correct result. If the parameter pack is empty, the
code
init
value is returned.

What happens if a unary fold expression is applied to an empty parameter pack?

It results in a compile-time error.

Fold expressions significantly enhance the expressiveness and efficiency of modern C++ code, particularly in generic programming and metaprogramming.

Learning Resources

C++ Fold Expressions Explained (cppreference.com)(documentation)

The official and most comprehensive reference for C++ fold expressions, detailing syntax, semantics, and examples.

Fold Expressions in C++17 (LearnCpp.com)(tutorial)

A clear and beginner-friendly explanation of fold expressions with practical code examples and step-by-step guidance.

Modern C++: Fold Expressions (YouTube)(video)

A video tutorial demonstrating the power and usage of fold expressions in C++17, often featuring live coding.

C++17 Fold Expressions: A Powerful Tool for Variadic Templates (The Cherno)(video)

A detailed video explanation from a popular C++ educator, covering the mechanics and benefits of fold expressions.

Effective Modern C++: Item 23 - Prefer Variadic Templates to Overloading (Scott Meyers)(blog)

While not solely about fold expressions, this chapter discusses the context of variadic templates where fold expressions shine, offering insights into best practices.

C++17: Fold Expressions (Jason Turner - C++ Weekly)(video)

A concise and focused video explaining the core concepts and syntax of C++17 fold expressions.

Variadic Templates and Fold Expressions in C++17 (GeeksforGeeks)(blog)

A comprehensive article covering variadic templates and how fold expressions simplify their usage with numerous code examples.

C++ Fold Expressions (Microsoft Docs)(documentation)

Official documentation from Microsoft on fold expressions, often with examples tailored for Visual Studio users.

C++17 Fold Expressions - A Deep Dive (Stack Overflow)(blog)

A community discussion on Stack Overflow providing various use cases, solutions to common problems, and expert opinions on fold expressions.

The C++ Programming Language (Bjarne Stroustrup)(paper)

While not a direct link to fold expressions, Stroustrup's seminal work provides the foundational understanding of C++ features, including the context for variadic templates and their evolution.