1

I've seen some people talk about the new abstraction of C++17 in for ranged loops, where one can use multiple iterators/values/references:

for(auto&& [output1, output2] : container)
{...}

I've been trying to find an explanation on Google for it, unsuccessfully, since I believe I'm not using the right terminology. In any case I'd be happy if somebody had a link to the cppreference, as well as answer these questions:

1. Are we using "&&" because [output1, output2] as a whole is an rvalue?

2. Let's assume that output1 and output2 are both of type int. What is the type of "auto"? In other words, what kind of (rvalue?) object is [output1, output2], in case I wanted to not use "auto" and declare it specifically? (Maybe a tuple?)

3. What is happening under the hood? Are two iterators being used behind the scenes (see below)? What would be the non C++17 implementation using real iterator objects?

for(Container::iterator it1 =..., Container::iteratorit2 = ...; it1!=..., it2!=...; ++it1, ++it2)
{...}
Michel H
  • 317
  • 3
  • 10
  • 5
    [structured_binding](https://en.cppreference.com/w/cpp/language/structured_binding). (and simpler to see it outside of for loop which is just one possible place to use it). – Jarod42 Apr 12 '21 at 14:46
  • 3
    The `auto &&[a, b] = ...;` syntax is a [structured binding](https://en.cppreference.com/w/cpp/language/structured_binding). I'm not familiar enough with them to answer off the top of my head, but that should give you a starting point. – Quentin Apr 12 '21 at 14:46
  • 2
    Also, `auto&&` is a _forwarding reference_, not an rvalue. Understanding that should cover questions 1. and 2. – Drew Dormann Apr 12 '21 at 14:50
  • 2
    It allows `auto [a, b] = std::pair(42, true);` and `std::map` use `std::pair`. (`std::pair` is a tuple-like class). – Jarod42 Apr 12 '21 at 14:50
  • 2
    Dupe of Q(1,2) https://stackoverflow.com/questions/49728626/do-structured-bindings-and-forwarding-references-mix-well Dupe of Q3 https://stackoverflow.com/questions/45480824/ – Drew Dormann Apr 12 '21 at 14:54
  • Thanks everyone. Jarod42: defining it with an ```std::pair``` might be allowed, but it might be just casting it to a pair. I'm interested in understanding the intrinsic type of if. But in any case, I think it'll be answered in the documents/references I got. – Michel H Apr 12 '21 at 15:03
  • @DrewDormann This is pedantic, but I don't believe `auto&&` is formally considered a "forwarding reference". A forwarding reference would deduce PRValues as value types (e.g. `T&& x = 5` as a template will deduce `T` as `int`, not `int&&`) -- but `auto&& x = 5` will have `decltype(x)` as `int&&`. This is just using reference collapsing, which would occur the same if you did `type&&` where `type` was an L or R-value reference. – Human-Compiler Apr 12 '21 at 15:12

0 Answers0