Home > Article > Backend Development > 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:
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!