Variadic Functions

Recursion vs Fold Expressions

When should I use fold expressions over recursive variadic function calls?

Abstract art representing computer programming

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 << ", ";

// 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

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.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved