Auto&& in range-based loop... which digestive for students?

Dear ROOTers,

I noticed that in the ROOT main page (code snippet about the TTreeReader facility) you suggest the use of the “auto&&” in the range-based loops.

I learned (and it took some effort) that this is the most generic approach that can cover also corner cases like vector.

When are you showing this to total-beginners students (physicists not computer scientists), how do you sell this without mentioning “universal reference” and “reference collapsing”? The only answer that I have found so far is “believe me for the moment and if really interested read a book”.

Moreover, googling around, I understood that there is a corner case that is not well managed by this universal reference type deduction: if the reference is used in a function overloaded with both T& and const T& signatures, the non-const version would be silently selected, while a “const auto&” would address the selection to the const version.

Have I understood right this subtlety?

The fact that the compiler makes a silent choice isn’t worse than having a compiler error when I use “auto&” for a vector ? For a student would be very hard to guess the problem, while the compilation error would trigger maybe some question to an expert.

Especially in the framework of that code snippet about the access to TTree data, I typically want just to read the TTree data, and maybe a “const auto&” is more explicative of what I am doing, besides being easier to explain to beginners.

I would like to hear your opinions taking into account the specific environment of “physics students learning this analysis tool” rather than just a generic c++ discussion.


Hi Matteo,

thanks for the long but focused message: Iet’s keep our attention on the didactic aspects as you suggest.
It is my opinion that being a teacher in the context of higher education is a challenging role. As a lecturer, you have to guarantee to all students the right to assimilate the concepts conveyed. At the same time, you shall feel the need to promote and foster innovation, for example discussing topics at the bleeding edge of scientific progress and technological advancements.
In general, I was never wrong when assuming that my audience as extraordinarily smart - we should not be afraid to show to students advanced concepts without discounts. It is fair to aim to excellence while keeping an eye on the overall set of students.
I share your point of not leaving learners behind. As you already underlined, I think it is good practice to advance in steps (“believe me for the moment”,“we’ll see this together later”, “if you are more interested you look at”) and in most cases this works quite well. I even has the effect of (further) motivating part of the audience, beyond being, to use your words, “a digestive”, for another part.