Calling a Function on Variadic Template Arguments
In C , one may desire to design a function that can operate seamlessly on an arbitrary number of arguments of various types. While recursive template specialization allows for such functionality, it produces a substantial amount of redundant code. To address this issue, a more efficient approach is sought.
C 17 Fold Expression Solution
In C 17, a straightforward solution is provided by the fold expression:
(f(args), ...);
This expression facilitates the sequential invocation of f on each argument in the args variadic pack. However, if f returns an object with an overloaded comma operator, the following syntax should be used:
((void)f(args), ...);
Pre-C 17 Solution
Prior to C 17, a typical approach involved employing a list initializer with an intentionally non-void return type:
{ print(Args)... }
However, this requires wrapping the expression in an unused variable to prevent compilation errors due to the void return type of print:
using expand_type = int[]; expand_type{ (print(Args), 0)... };
To enhance the reusability of this pattern, a macro can be defined:
#define SO_EXPAND_SIDE_EFFECTS(PATTERN) ::so::expand_type{ 0, ((PATTERN), 0)... } SO_EXPAND_SIDE_EFFECTS(print(Args));
To mitigate the potential allocation of large arrays, a custom struct can be utilized:
namespace so { struct expand_type { template <typename... T> expand_type(T&&...) {} }; }
The above is the detailed content of How do you call a function on a variadic template arguments in C ?. For more information, please follow other related articles on the PHP Chinese website!