Introduction
Variadic templates allow you to create generic functions that can take a variable number of arguments. However, iterating over those arguments can be challenging. This article explores methods for iterating over packed variadic template argument lists, including a comprehensive solution using fold expressions.
Method 1: Iterate Over Homogeneous Type Inputs
If your inputs are all of the same type, you can use a macro or lambda function to loop through them. For example:
<code class="cpp">#include <iostream> #define FOREACH_INPUT(...) (([](auto &&... inputs) { for (auto input : { __VA_ARGS__ }) { std::cout << input << std::endl; } })(inputs))
Usage:
<code class="cpp">FOREACH_INPUT(1, 2, 3, 4, 5);
Method 2: Fold Expressions (>= C 17) For mixed-type inputs, fold expressions provide a concise and powerful approach. Consider the following example: Enhanced Fold Expression with Break/Return If you need breaks or returns in your loop, consider the following workarounds: The above is the detailed content of How to Effectively Iterate Over Packed Variadic Template Argument Lists in C ?. For more information, please follow other related articles on the PHP Chinese website!<code class="cpp">#include <iostream>
#include <utility>
template <class ... Ts>
void Foo (Ts &&... inputs)
{
int i = 0;
([&]
{
std::cout << "input " << ++i << " = " << inputs << std::endl;
} (), ...);
}
int main()
{
Foo(2, 3, 4u, (int64_t) 9, 'a', 2.3);
}</code>
<code class="cpp">#include <iostream>
#include <utility>
template <class ... Ts>
void Foo (Ts &&... inputs)
{
int i = 0;
try {
([&]
{
std::cout << "input " << ++i << " = " << inputs << std::endl;
if (inputs == 'a') throw 1;
} (), ...);
} catch (...) {
}
}
int main()
{
Foo(2, 3, 4u, (int64_t) 9, 'a', 2.3);
}</code>
<code class="cpp">#include <iostream>
#include <utility>
template <class ... Ts>
void Foo (Ts &&... inputs)
{
int i = 0;
bool exit = false;
auto process_input = [&](auto &&input) mutable {
if (input == 'a') {
std::cout << "Found 'a'. Breaking loop." << std::endl;
exit = true;
return;
}
std::cout << "input " << ++i << " = " << input << std::endl;
};
(process_input(inputs), ...);
if (!exit)
std::cout << "Finished looping through all inputs." << std::endl;
}
int main()
{
Foo(2, 3, 4u, (int64_t) 9, 'a', 2.3);
}</code>