In the book "Effective modern C++", at the item 3 there is written this piece of code:
template<typename Container, typename Index>
decltype(auto)
authAndAccess(Container&& c, Index i)
{
authenticateUser();
return std::forward<Container>(c)[i];
}
I don't understand why you call std::forward
? If c
is an rvalue reference, what does it change to call the operator[]
on a rvalue instead on a lvalue? For me c[i]
should be enough.
PS: I understand the purpose of std::forward
when the variable is a parameter of a function as:
template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&&... params)
{
return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
}
It’s possible that operator[] for Container has been overloaded for rvalues and lvalues.
auto Container::opeartor[](int i) && -> Container::value_type&;
auto Container::opeartor[](int i) & -> Container::value_type&;
If so, we want to make sure that if c was initialized with an rvalue, we call the rvalue version of operator[] on c. It’s certainly not common to overload operator[] to behave differently for lvalues and rvalues, but it’s possible, so in truly generic code, we need to apply std::forward to c before forwarding it to operator[].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With