Calling Functions on Variadic Template Arguments
The goal is to implement a print() function that takes a variable number of arguments and executes an arbitrary function on each argument. This is desired as a compact alternative to the recursive implementation with separate specializations for each argument type.
C 17 Solution
In C 17, this can be achieved using a fold expression:
(f(args), ...);
This expression expands the arguments in args and calls f() on each one. If f() returns an object with an overloaded comma operator, use:
((void)f(args), ...);
Pre-C 17 Solution
For versions of C prior to C 17, a common approach is to use a list initializer to expand the arguments:
{ print(Args)... }
However, print() returns void, so to avoid a compile error, the code can be modified as shown below:
using expand_type = int[]; expand_type{ (print(Args), 0)... };
This works for variadic arguments, but there are some caveats to consider. To make this pattern reusable, a macro can be created:
#define SO_EXPAND_SIDE_EFFECTS(PATTERN) ::so::expand_type{ 0, ((PATTERN), 0)... }
However, to prevent potential issues with overloaded comma operators, the macro can be updated as follows:
#define SO_EXPAND_SIDE_EFFECTS(PATTERN) ::so::expand_type{ 0, ((PATTERN), void(), 0)... }
Pre-C 17 solutions may also require additional considerations to avoid unnecessary memory allocation.
The above is the detailed content of How to Call Functions on Variadic Template Arguments in C ?. For more information, please follow other related articles on the PHP Chinese website!