【发布时间】:2021-09-12 10:19:34
【问题描述】:
引自“Effective Modern C++”的第 3 条(“理解 decltype”):
但是,我们需要更新模板的实现以使其符合 与 Item 25 的告诫将 std::forward 应用于通用引用:
template<typename Container, typename Index>
decltype(auto) authAndAccess(Container&& c, Index i)
{
authenticateUser();
return std::forward<Container>(c)[i];
}
为什么我们在“authAndAccess”的最后一条语句中转发“c”?我理解当我们将参数从原始函数中传递给另一个函数时需要转发(以便能够正确调用采用右值引用的重载版本,或者如果存在按值获取参数的重载版本,那么我们可以移动而不是复制),但是在上面的例子中调用 indexing-operator 时 std::forward 给我们带来了什么好处?
下面的示例还验证了使用 std::forward 不允许我们从 authAndAccess 返回右值引用,例如,如果我们希望能够使用返回值移动(而不是复制)。
#include <bits/stdc++.h>
void f1(int & param1) {
std::cout << "f1 called for int &\n";
}
void f1(int && param1) {
std::cout << "f1 called for int &&\n";
}
template<typename T>
void f2(T && param) {
f1(param[0]); // calls f1(int & param1)
f1(std::forward<T>(param)[0]); // also calls f1(int & param1) as [] returns an lvalue reference
}
int main()
{
std::vector<int> vec1{1, 5, 9};
f2(std::move(vec1));
return 0;
}
【问题讨论】: