4

Many times I saw code like this:

template<typename Collection> void Foo(Collection&& c) { for (auto&& i : std::forward<Collection>(c)) // do something with i } 

For all STL containers (except vector<bool>) i has type of lvalue reference. Is any practical sense to type auto&& in this case?

1 Answer 1

4

As you said, the perfect example of where you don't have an lvalue is std::vector<bool>. Using auto& will not compile, as a prvalue is returned from the iterator.

Also, it happened to me some times to make ranges that did not returned an lvalue from its iterator.

Also, the upside of using auto&& is that there is no cases where it won't work. Even of you have a bizarre case where your iterator yield a const rvalue reference, auto&& will bind to it.

For teaching, it's also easier to tell "use auto&& in your for loops." because it will not cause copy and work everywhere.

There where also a proposal to allow implicit auto&& and enable the syntax for (x : range) (I cannot remember which one is it. If you know it, please tell me in the comments)

Sign up to request clarification or add additional context in comments.

2 Comments

Terse for loops, if memory serves.
That proposal crashed and burned. I don't see much point in mentioning it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.