在《Effective modern C++》一书中,在第3项中写了这段代码:
template<typename Container, typename Index>
decltype(auto)
authAndAccess(Container&& c, Index i)
{
authenticateUser();
return std::forward<Container>(c)[i];
}
Run Code Online (Sandbox Code Playgroud)
我不明白你为什么打电话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)...));
}
Run Code Online (Sandbox Code Playgroud) c++ ×1