Home >Backend Development >C++ >How to Iterate Over Variadic Template Argument Lists in C ?
Iterating over Variadic Template Argument Lists
Packed variadic template argument lists, while powerful, can pose challenges in accessing individual arguments. This issue is particularly relevant when one needs to iterate over such lists to segregate arguments based on their types.
To achieve this, one option is to leverage the fold expressions introduced in C 17. By utilizing a callable, a lambda expression in this case, one can define a loop that iterates through the arguments and performs desired operations.
Here's an example:
<code class="cpp">#include <iostream> template <class ... Ts> void Foo(Ts && ... inputs) { int i = 0; // Lambda that executes for each passed argument. ([&] { ++i; std::cout << "input " << i << " = " << inputs << std::endl; }(), ...); } int main() { Foo(2, 3, 4u, (int64_t)9, 'a', 2.3); return 0; }</code>
In this example, the lambda is exceptionally concise, but even more complex operations can be performed within the loop. It's important to note that this technique requires C 17 or later.
For scenarios where returning or breaking out of the iteration is necessary, try/throw and variable/if switch approaches are available but should be considered code smells and used only if unavoidable.
The above is the detailed content of How to Iterate Over Variadic Template Argument Lists in C ?. For more information, please follow other related articles on the PHP Chinese website!