Empty Parameter Packs in Fold Expressions
How do fold expressions handle empty parameter packs?
Fold expressions handle empty parameter packs differently depending on whether they are unary folds or binary folds. Here's how empty parameter packs are treated in each case:
Unary Folds
Unary folds expect the parameter pack to have at least one element. If the parameter pack is empty, it results in a compilation error.
For example, in this case, calling Product()
with an empty parameter pack triggers a compilation error because a unary fold over the *
operator requires a non-empty parameter pack.
To handle empty parameter packs with unary folds, you need to provide an explicit base case or use a binary fold instead.
template <typename... Types>
auto Product(Types... Args) {
return (... * Args);
}
int main() {
// Compilation error
Product();
}
error: a unary fold expression over '*' must have a non-empty expansion
Binary Folds
Binary folds handle empty parameter packs by using the identity value of the operator as the result of the fold expression. For example:In this case, calling Sum()
with an empty parameter pack results in the identity value of the +
operator, which is 0
.
#include <iostream>
template <typename... Types>
auto Sum(Types... Args) {
return (0 + ... + Args);
}
int main() {
int EmptySum = Sum();
std::cout << EmptySum;
}
0
The binary fold expression (0 + ... + Args)
evaluates to 0
when Args
is empty.
The identity value depends on the operator used in the binary fold
- For addition (
+
), the identity value is0
. - For multiplication (
*
), the identity value is1
. - For logical AND (
&&
), the identity value istrue
. - For logical OR (
||
), the identity value isfalse
. - For comma (
,
), the identity value isvoid()
.
To ensure that your fold expressions handle empty parameter packs correctly, you can:
- Use binary folds with an appropriate identity value when you need to support empty parameter packs.
- Provide an explicit base case or specialization for empty parameter packs if using unary folds.
- Be aware of the operators that have an identity value and choose them appropriately based on your requirements.
By understanding how fold expressions handle empty parameter packs, you can write more robust and flexible code that works correctly in both empty and non-empty scenarios.
Fold Expression
An introduction to C++17 fold expressions, which allow us to work more efficiently with parameter packs