Home > Backend Development > C++ > 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
Release: 2024-11-11 03:51:02
Original
326 people have browsed it

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

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

((void)f(args), ...);
Copy after login

Pre-C 17 Solution

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

{ print(Args)... }
Copy after login

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

{ (print(Args), 0)... }
Copy after login

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

{ 0, (print(Args), 0)... }
Copy after login

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

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

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

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

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!

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