【发布时间】:2020-10-23 13:06:23
【问题描述】:
感谢您对理解 std::forward 实现的帮助。
std::forward 和模板函数中标准转换为 T&& 的区别是什么? 至少在这个例子中,它们似乎都正确地完成了转发工作。 LValue 被转发到 LValue 重载,RValue 被转发到 RValue 重载。
struct DemoPerfectForwardVsRefRefCast
{
void overloaded(int const &arg) { std::cout << "receive by lvalue\n"; }
void overloaded(int && arg) { std::cout << "receive by rvalue\n"; }
template< typename t >
void forwarding(t && arg) {
std::cout << "via std::forward: ";
overloaded(std::forward< t >(arg)); // forwards correctly
std::cout << "via && cast: ";
overloaded(static_cast<t&&>(arg)); // seems to also forward correctly
}
void demo()
{
std::cout << "initial caller passes rvalue:\n";
forwarding(5);
std::cout << "initial caller passes lvalue:\n";
int x = 5;
forwarding(x);
}
};
通用引用 + 引用折叠 + 静态转换为 T&& 足够了吗?
在 Visual Studio 2017 中,std::forward 的定义以不同方式实现,有两个模板函数,一个带有 T& 参数,一个带有 T&& 参数。 那有必要吗? 比演员阵容更好吗?
【问题讨论】:
-
eli.thegreenplace.net/2014/… 还具有两个模板函数实现
-
更重要的是,标准将
std::forward<T>(x)的返回值定义为static_cast<T&&>(x)。
标签: c++ rvalue perfect-forwarding function-templates