Viktor
Viktor

Reputation: 1054

What profit of universal reference usage in range based loop?

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?

Upvotes: 4

Views: 454

Answers (1)

Guillaume Racicot
Guillaume Racicot

Reputation: 41780

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)

Upvotes: 4

Related Questions