I wrote a simple variadic template function and I'm trying to understand why it doesn't work. (Its output counterpart works perfectly.)
#include <iostream>
void read() {}
template<class curr_t, class... rest_t>
void read(curr_t &var, rest_t... rest)
{
std::cin >> var;
read(rest...);
}
int main()
{
int a = 0, b = 0, c = 0;
read(a, b, c); //input: 1 2 3
std::cout << a << b << c; //output: 1 0 0
std::cin.ignore();
std::cin.get();
}
As can be seen from the comments, I input 1 2 3
for a b c
and the output I get is 1 0 0
. As it is apparent, only a
saves its value. Can someone explain why this happens and what can I do to fix it? Thanks!
EDIT::
Yes, apparently I had the concept of parameter packs wrong!
I was also trying to do the following: rest_t... &rest
which gives me a compiler error.
Instead if I write rest_t&... rest
it works as intended. I suppose it was just a syntax error on my side! Thanks to whoever posted this as an answer and deleted his answer a minute later! D:
a
is passed by reference but the others are copied: when you call it recursively, they are, yes, taken by reference, but they refer to a variable previously passed by value so it won't be modified externally.
template<class curr_t, class... rest_t>
void read(curr_t &var, rest_t&... rest)
// ^
{
std::cin >> var;
read(rest...);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With