容器调用运算符[]上的c++std::forward
c++ std::forward on the container calling operator[]
在《有效的现代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)...));
}
Container的运算符[]可能已经重载了右值和左值。
auto Container::opeartor[](int i) && -> Container::value_type&;
auto Container::opeartor[](int i) & -> Container::value_type&;
如果是这样的话,我们想确保如果c是用右值初始化的,我们在c上调用运算符[]的右值版本。重载运算符[]对左值和右值的行为不同当然是不常见的,但这是可能的,所以在真正的泛型代码中,我们需要在将其转发给运算符[]之前将std::forward应用于c。
相关文章:
- 如何检测 std::vector::emplace_back 上的隐式转换损失整数精度
- 警告:忽略模板参数上的属性..在 std::unique_ptr (-wignore 属性)的声明中
- DRD 报告"conflicting load" std::mutex::lock 上的错误
- 为什么在Visual Studio 2013上的std::this_thread::sleep_for上死锁
- 在 MacOS 上的 Visual Studio Code 中C++ - std::make_unique
- std::is_same在类型相等检查上的荒谬行为
- std::vector上的嵌套循环
- std::cin >>上的参数无效
- 在不同数量的行上与 C++ std::regex_replace 匹配
- std::atomic::fetch_add是x86-64上的串行化操作
- std::move() 或其在局部变量上的显式等价物可以允许 elision 吗?
- 互锁变量访问(在布尔值上)和 std::atomic_flag 之间的区别
- std::transform C++ 上的致命错误
- 英特尔编译器 (C++) 问题与 std::vector 上的 OpenMP 缩减
- 具有多个空成员的 std::元组上的比较无法在 GCC 上编译
- 为什么 std::cbegin() 不调用容器上的 .cbegin()?
- 原始数组和 std::array 在 clang++ 和 VC++ 上的不同迭代器行为
- 如何在任何一个轴上找到 std::vector<std::p air<int, int>> 上的 std::max_element?
- Visual 2015 上的 std::get_time 不会在错误的日期失败
- 容器调用运算符[]上的c++std::forward