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

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Passing Parameter Packs by Value or Reference
When should I pass the parameters in a parameter pack by value, reference, const reference, or forwarding reference?
Capturing Lvalues and Rvalues in Variadic Functions
How can I write a variadic function that can accept both lvalue and rvalue arguments?
Zero Argument Variadic Functions
What happens if I call a variadic function with no arguments?
Performance Considerations with Variadic Functions
Are there any performance implications to using variadic functions?
Why use parameter packs instead of just va_args?
I can already write variadic functions in C++ using va_args. Why would I use parameter packs instead?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant