Link package passed by reference

I wrote a simple variable template function, and I'm trying to understand why it does not work. (Its output counterpart works fine.)

#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 enter 1 2 3 for abc , and the output I get is 1 0 0 . Apparently, only a retains its value. Can someone explain why this is happening, and what can I do to fix it? Thanks!

EDIT :: Yes, apparently, I was mistaken in the concept of parameter packages! I also tried 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 for sending this as an answer, and deleting his answer in a minute! D:

+5
source share
1 answer

a is passed by reference, and the rest are copied: when you call it recursively, yes they are taken by reference, but they refer to a variable previously passed by value, so it will not be changed externally.

 template<class curr_t, class... rest_t> void read(curr_t &var, rest_t&... rest) // ^ { std::cin >> var; read(rest...); } 
+5
source

Source: https://habr.com/ru/post/1234470/


All Articles