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:
template
void Foo (Ts && ... inputs)
{
int i = 0;
([&]
{
// Do things in your "loop" lambda
i;
std::cout << "input " << i << " = " << inputs << std::endl;
} (), ...);
}
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:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3