C ++ std :: forward for container call operator []

In the book "Effective Modern C ++" in paragraph 3, this piece of code is written:

template<typename Container, typename Index>
decltype(auto)
authAndAccess(Container&& c, Index i)
{
  authenticateUser();
  return std::forward<Container>(c)[i];
}

I do not understand why you call std::forward? If it cis a reference to an rvalue, what will it change to call operator[]on an rvalue instead of an lvalue? It c[i]should be enough for me .

PS: I understand the purpose std::forwardwhen a variable is a function parameter like:

template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&&... params)
{
  return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
}
+4
source share
1 answer

It is possible that the [] operator for the Container is overloaded for r values ​​and lvalues.

auto Container::opeartor[](int i) && -> Container::value_type&;
auto Container::opeartor[](int i) & -> Container::value_type&;

, , c rvalue, rvalue- [] c. , , [] - lvalues ​​ rvalues, , std:: forward c, [].

+3

All Articles