Home  >  Article  >  Backend Development  >  How Can C 17 Fold Expressions Simplify Variadic Function Invocation?

How Can C 17 Fold Expressions Simplify Variadic Function Invocation?

Barbara Streisand
Barbara StreisandOriginal
2024-11-19 11:17:02914browse

How Can C  17 Fold Expressions Simplify Variadic Function Invocation?

Simplifying Variadic Function Invocation Using C 17 Folds

Variadic template arguments provide a convenient way to work with functions that accept a variable number of arguments. However, creating recursive chains to call functions on each variadic argument can lead to redundant code generation. Here's how you can overcome this issue using C 17 fold expressions or a pre-C 17 solution.

C 17 Fold Expression:

(f(args), ...);

This fold expression can be used to call a function on all variadic template arguments, resulting in a single N-arg function call.

Pre-C 17 Solution:

1. Wrap Function in Identifier:

Transform the function to return an int, which can be used as a dummy argument in an initializer list:

int print_wrap(const T& t) {
  print(t);
  return 0;
}

2. Create List Initializer:

Use a list initializer to expand the variadic arguments and call the modified function:

{ print_wrap(args)... }

3. Define Helper Namespace:

To make this approach reusable, define a helper namespace:

namespace so {
  using expand_type = int[];
}

#define SO_EXPAND_SIDE_EFFECTS(PATTERN) ::so::expand_type{ 0, ((PATTERN), 0)... }

4. Usage:

SO_EXPAND_SIDE_EFFECTS(f(args));

Advantages:

  • Generates only a single function call with N arguments.
  • Supports functions with overloaded comma operators.
  • Ensures left-to-right evaluation of arguments.

The above is the detailed content of How Can C 17 Fold Expressions Simplify Variadic Function Invocation?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn