Recursion vs Fold Expressions
When should I use fold expressions over recursive variadic function calls?
Fold expressions, introduced in C++17, provide a concise way to apply an operation to each element in a parameter pack without explicit recursion. They can be a good choice over recursive variadic function calls in certain situations:
When the operation is simple and can be expressed as a fold:
- Summing values
- Printing values
- Performing a logical AND or OR on values
When performance is a concern:
- Fold expressions can reduce the amount of generated code compared to recursive function calls
- Recursive variadic functions can lead to deep template instantiations and potentially slower compilation times
However, recursive variadic functions are still useful when:
- The operation is complex and can't be easily expressed as a fold
- You need more fine-grained control over the operation applied to each element
- You need to perform different operations depending on the position or type of the element
For example, consider printing the elements of a parameter pack:
#include <iostream>
// Recursive variadic function
template <typename T, typename... Types>
void PrintRecursive(T First, Types... Rest) {
std::cout << First;
if constexpr (sizeof...(Rest) > 0) {
std::cout << ", ";
PrintRecursive(Rest...);
}
}
// Fold expression
template <typename... Types>
void PrintFold(Types... Args) {
(std::cout << ... << Args);
}
int main() {
PrintRecursive(1, 2.0, "three");
std::cout << '\n';
PrintFold(1, 2.0, "three");
}
1, 2, three
12three
The fold expression is more concise but doesn't add separators between elements. The recursive version allows for more control but is more verbose.
In general, prefer fold expressions for simple operations where performance is a concern. Use recursive variadic functions for more complex or fine-grained operations.
Variadic Functions
An introduction to variadic functions, which allow us to pass a variable quantity of arguments