Home  >  Article  >  Backend Development  >  How to Invoke a Function on All Variadic Template Arguments in C ?

How to Invoke a Function on All Variadic Template Arguments in C ?

Susan Sarandon
Susan SarandonOriginal
2024-11-11 03:51:02254browse

How to Invoke a Function on All Variadic Template Arguments in C  ?

C Variadic Templates: Invoking a Function on All Template Arguments

In C , it's often desirable to iterate through variadic template arguments and perform a specific operation, such as calling a function. This can be achieved using either:

C 17 Fold Expression

(f(args), ...);

However, if the called function potentially returns an object with an overloaded comma operator, you should use:

((void)f(args), ...);

Pre-C 17 Solution

A common approach is to leverage list-initialization and perform the expansion within it:

{ print(Args)... }

Since print() returns void, you can workaround the issue by returning int:

{ (print(Args), 0)... }

To ensure this works with any number of arguments, you can make the pack always have at least one element:

{ 0, (print(Args), 0)... }

You can encapsulate this pattern into a reusable macro:

namespace so {
    using expand_type = int[];
}

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

To handle overloaded comma operators, you can modify the macro:

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

If you're concerned about unnecessary memory allocation, you can define a custom type that supports list-initialization but doesn't store data:

namespace so {
    struct expand_type {
        template <typename... T>
        expand_type(T&amp;&amp;...) {}
    };
}

The above is the detailed content of How to Invoke a Function on All Variadic Template Arguments in C ?. 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