Reputation: 1682
I've seen many example codes that use recursion to extract the values from a parameter pack. Is there any way, other than recursion, to extract the values from a parameter pack?
Upvotes: 0
Views: 840
Reputation: 1682
It turns out that it there's a workaround. C++ parameter pack expansions can be used as for each loops:
#include <iostream>
template <int ... ints>
constexpr int product() {
int ret = 1;
auto _ = {
([&](int i) -> int {
ret *= i;
return i;
})(ints)...
};
return ret;
}
int main() {
std::cout << product<2, 6, 3>() << '\n';
return 0;
}
The problems are:
Upvotes: 1
Reputation: 29985
Depending on what you want to do, you can use C++17 fold expressions:
template <int ... ints>
constexpr int product() {
return (ints * ...);
}
Upvotes: 1
Reputation: 20936
You can forward all pack parameters as a tuple, then call get<0>
:
template<class ... Args>
void foo(Args&& ... args) {
auto&& first = std::get<0>(std::forward_as_tuple(std::forward<Args>(args)...));
}
Upvotes: 1