How to Iterate Over a Packed Variadic Template Argument List
In C , iterating over a packed variadic template argument list poses a challenge due to the inability to know the number of arguments and retrieve data from them individually. This issue is further compounded by the use of a macro in constructing the function, which precludes recursive calls.
To address this, the provided solution employs a custom type, any, which can hold different types of data. By passing this type to a variadic template, the arguments are expanded into a vector of any objects. Subsequently, the individual elements of this vector can be retrieved using specialized getter functions (get
While this method accomplishes the task, it does require verbose function calls, such as foo(arg(1000)). To simplify this, we seek a more concise iteration method or an equivalent of std::get() for packed variadic template argument lists.
Solution using STL Fold Expressions and Lambda
For C 17 and later, fold expressions can be utilized along with a lambda function to achieve iteration. The lambda can perform arbitrary operations within the loop, including incrementing a counter and printing the current argument:
<code class="cpp">template <class ... Ts> void Foo (Ts && ... inputs) { int i = 0; ([&] { // Do things in your "loop" lambda ++i; std::cout << "input " << i << " = " << inputs << std::endl; } (), ...); }</code>
This method provides a more succinct and legible iteration mechanism.
Alternatives for Dealing with Loop Breaks
While the aforementioned solution accomplishes the task, it lacks the ability to implement breaks or returns within the loop. To address this, we can utilize workarounds such as:
The above is the detailed content of How Can We Iterate Over a Packed Variadic Template Argument List Concisely?. For more information, please follow other related articles on the PHP Chinese website!