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 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 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
+
), the identity value is 0
.*
), the identity value is 1
.&&
), the identity value is true
.||
), the identity value is false
.,
), the identity value is void()
.To ensure that your fold expressions handle empty parameter packs correctly, you can:
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.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to C++17 fold expressions, which allow us to work more efficiently with parameter packs