Home > Backend Development > C++ > body text

How to Call Functions on Variadic Template Arguments in C ?

Patricia Arquette
Release: 2024-11-24 16:31:14
Original
291 people have browsed it

How to Call Functions on Variadic Template Arguments in C  ?

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), ...);
Copy after login

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), ...);
Copy after login

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)... }
Copy after login

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)... };
Copy after login

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)... }
Copy after login

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)... }
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template