Home > Backend Development > C++ > body text

How do you call a function on a variadic template arguments in C ?

DDD
Release: 2024-11-10 22:02:03
Original
157 people have browsed it

How do you call a function on a variadic template arguments in C  ?

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

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

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

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template