Iterating Over Packed Variadic Template Argument Lists
In C , iterating over a packed variadic template argument list poses specific challenges due to the lack of compile-time reflection abilities. However, there are techniques that allow us to tackle this task.
Understanding the Problem
The goal is to iterate over a pack of template arguments, extracting data of specific types (e.g., int, char*, float) and storing it in separate vectors. Additionally, a vector is needed to keep track of the order in which arguments appeared.
Approaching the Solution
Using Fold Expressions with Lambda:
For mixed-type inputs, C 17 fold expressions can be used alongside a lambda expression. The lambda encapsulates the looping behavior, incrementing a counter and printing each input's value along with its position.
<code class="cpp">template<class ... Ts> void Foo(Ts && ... inputs) { int i = 0; ([&]() { ++i; std::cout << "input " << i << " = " << inputs << std::endl; }(), ...); }
Handling Return/Break Statements:
If return or break statements are required within the loop, workarounds can be implemented:
Custom Macro Approach:
An alternative approach involves creating a custom macro that constructs a type to hold all the arguments and then expands it inside a vector. While this is a non-standard method, it can achieve the desired functionality.
<code class="cpp">struct any { void do_i(int e) { INT = e; } void do_f(float e) { FLOAT = e; } void do_s(char* e) { STRING = e; } int INT; float FLOAT; char* STRING; }; #define def(name) \ template<typename... T> \ auto name(T... argv) -> any { \ std::initializer_list<any> argin = { argv... }; \ std::vector<any> args = argin; #define get(name, T) get<T>()(args[name]) #define end }</code>
This approach requires manually calling arg() functions to create an any instance for each argument.
Conclusion
Iterating over packed variadic template argument lists in C requires innovative solutions. The approaches discussed here address this challenge, allowing for efficient handling of mixed-type arguments while maintaining portability and cross-platform compatibility.
The above is the detailed content of How to Iterate Over Packed Variadic Template Argument Lists in C ?. For more information, please follow other related articles on the PHP Chinese website!