Namespaces
Variants
Views
Actions

Talk:cpp/language/range-for

From cppreference.com

[edit] Use technical detail of standard

The standard says that really "auto __begin = std::Range<_RangeT>::begin(__range)", but I abbreviated this to just "__begin = __range.begin()". Do you think this loses accuracy. It improves readability. -- Jaredgrubb 08:33, 2 July 2011 (PDT)

@Jaredgrubb: Are you reading an up-to-date version of the draft? I believe n3242 is the most up-to-date, and I see no mention in it of the <iterator_concept> header, nor std::Range. --Benjamin Lindley 12:27, 2 July 2011 (PDT)

Ah, I was using n2243 [1], which I found a link to on the Clang pages. Looks like GCC is based on n2930 [2]. I cant find n3242. You have any advice on how to find the one in the "final" proposal - Jaredgrubb 17:49, 2 July 2011 (PDT)

Ok here's n3242 [3]. I'll review and fix the text.

[edit] Type inference

Does the type inference default to reference or value? I'm not entirely sure of this and it would probably be a good thing to mention on the page. --- Undeterminant 14:00, 30 April 2012 (PDT)

If you're referring to the keyword auto, it is explained on auto's page (to put it simple, auto makes the loop variable a copy of the container's element, auto& makes it a reference to the container's element, const auto& makes it a const reference). --Cubbi 19:46, 30 April 2012 (PDT)

[edit] auto&& IS NOT "int&&"

this example code comment is wrong: "for (auto&& i : v) // access by reference, the type of i is int&&"

auto&& results in i being "int&" as it is a universal reference

changing "auto&&" to "int&&" results in the expected compiler error

more about why this happens: http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers

You're right of course, good job catching that bug so soon. --Cubbi (talk) 12:01, 19 November 2014 (PST)
Why the for(auto &&i : v) instead of for(auto &i : v)? If we add const in there as in for(const auto &&i) then clang complains "error: rvalue reference to type 'const A' cannot bind to lvalue of type 'A'" that makes me think that i is an rvalue reference. But if I take the const out and try to modify i in the loop, then the vector elements get modified, as if i was an lvalue reference to them. Completely confused - any hints as to what's going on? Which should one use: for(auto &&i : v) or for(auto &i : v)? -- CK
auto&& is neither lvalue nor rvalue, it's a forwarding reference. Catch by forwarding reference is the most general form (there was even a proposal to make that the default), as mentioned under Notes on this page. When iterating a vector (other than vector<bool>), you can also use regular lvalue references. --Cubbi (talk) 06:21, 15 February 2016 (PST)