Scott Meyers in his new book "Effective Modern C++" shows the following function as an example of using decltype(auto)
(page 28):
template<typename Container, typename Index>
decltype(auto)
authAndAccess(Container&& c, Index i)
{
authenticateUser();
return std::forward<Container>(c)[i];
}
My question is simple. Why do we need std::forward
applied to c
here? We are not passing c
anywhere, we are calling operator[]
on it. And none of standard containers have ref-qualified overloads (r-value/l-value overloads) of operator[]
.
So I see only two reasons for this std::forward
:
operator[]
.std::forward
on it. Period.Any other reasons?
Reason #1 is the relevant one. When you implement a generic function, you don't go by "What do these particular types I know about do?", but by "What do I know about the generic thing I am working with?".
The generic container doesn't say anything about reference qualification, so you forward.
Of course, reason #2 is much easier to remember and reason about, so you should follow that.
I don't think there are any other reasons.
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