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:
When performance is a concern:
However, recursive variadic functions are still useful when:
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.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to variadic functions, which allow us to pass a variable quantity of arguments