c ++ std :: forward在容器上调用operator []

时间:2016-03-26 23:32:47

标签: c++

在书#34;有效的现代C ++"中,在第3项中写了这段代码:

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

我不明白你拨打std::forward的原因?如果c是左值参考,那么在左值上调用operator[]而不是左值会更改什么?对我来说c[i]就足够了。

PS:当变量是函数的参数时,我理解std::forward的目的:

template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&&... params)
{
  return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
}

1 个答案:

答案 0 :(得分:3)

对于rvalues和左值,Container的operator []可能已经过载。

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

如果是这样,我们想确保如果c用rvalue初始化,我们在c上调用operator []的rvalue版本。重载operator []对于左值和右值的行为不一定是不常见的,但它是可能的,所以在真正的通用代码中,我们需要在将它转发给operator []之前将std :: forward应用于c。