Looping over Parameter Packs with Pack Expansion
In the provided code snippet, you intend to loop through a variable-length parameter pack using the pack expansion syntax. However, the code fails to compile with the error "parameter pack must be expanded in this context."
To resolve this issue, you need to place the pack expansion inside a context where it's permitted. One suitable location is within a braced-init-list. Consider the following modified code:
template<typename... Args> static void foo2(Args &&... args) { int dummy[] = { 0, ( (void) bar(std::forward<Args>(args)), 0) ... }; }
Here's how it works:
With this modification, the code will successfully compile and loop over the parameter pack.
C 17 Fold Expressions
In C 17, you can simplify the code using fold expressions:
((void) bar(std::forward<Args>(args)), ...);
This expression expands the pack and applies the specified operation (in this case, calling bar()) left-to-right.
The above is the detailed content of How Can I Correctly Loop Through a C Parameter Pack Using Pack Expansion?. For more information, please follow other related articles on the PHP Chinese website!