This example uses a common variadic template and function. I want to print out the arguments passed to f
:
#include
template <
There you go. You had several mistakes in your code, you can see the comments between the lines below:
#include
template
void print(T t) {
std::cout << t << std::endl;
}
// Base case, no args
void f() {}
// Split the parameter pack.
// We want the first argument, so we can print it.
// And the rest so we can forward it to the next call to f
template
void f(T &&first, Ts&&... rest) {
// print it
print(std::forward(first));
// Forward the rest.
f(std::forward(rest)...);
}
int main() {
f(2, 1, 4, 3, 5);
}
Note that using rvalue refs here makes no sense. You're not storing the parameters anywhere, so simply passing them by const reference should do it. That way you'd also avoid using std::forward
just to keep the (useless) perfect forwarding.
Therefore, you could rewrite f
as follows:
template
void f(const T &first, const Ts&... rest) {
print(first);
f(rest...);
}