c++ - 需要帮助理解 std::forward
问题描述
在C++ 中的完美转发和通用引用一文中,我有一个我不明白的时刻。在使用 std::forward 第一个案例解决完美转发段落中,我理解,但第二个没有。
The other case to handle is:
wrapper(42, 3.14f);
Here the arguments are rvalues, so T1 is deduced to int. We get the call func(forward<int>(e1), ...). Therefore, forward is instantiated with int and we get this version of it [3]:
int&& forward(int&& t) noexcept {
return static_cast<int&&>(t);
}
包装是
template <typename T1, typename T2>
void wrapper(T1&& e1, T2&& e2) {
func(forward<T1>(e1), forward<T2>(e2));
}
对于正向作者说在这种情况下使用了这个重载
template<class T>
T&& forward(typename std::remove_reference<T>::type& t) noexcept {
return static_cast<T&&>(t);
}
所以在调用 wrapper(42, 3.14f); 我们有
void wrapper(int&& && e1, float&& && e2) {
func(forward<T1>(e1), forward<T2>(e2));
推断为
void wrapper(int e1, float e2) {
func(forward<int>(e1), forward<float>(e2));
然后调用其中之一。因为它是向前的(typename std::remove_reference::type& t)我们仍然有
int&& forward(typename std::remove_reference<int>::type& t) noexcept
-->
int&& forward(typename int& t) noexcept
于是又来了
return static_cast<int& &&>(t);
这将返回 int&。但是在这个例子中我们应该得到 int&& 。所以我显然不明白一些事情。对我来说,似乎 typename std::remove_reference::type& t 总是会返回引用,所以 forward 的返回总是return static_cast<T& &&>(t);
需要帮助。
解决方案
推荐阅读
- python - 如何在 python 中从 int64 创建标量索引?
- html - 我的徽标图像未在 Html 中正确显示
- java - 我如何用java在hdf5文件中写入这个对象
- database - 安装了 IBM DB2 并创建了示例数据库。数据库已创建,但无法查看其中的任何表
- java - 带代理的 RestTemplate - 如何测试
- java - 读取 JSON 文件并将其转换为 HTML?
- powershell - Powershell根据日期范围标准删除文件夹文件
- excel - 更改打印机时 Excel 文档的布局会发生变化
- javascript - WebComponents - 在组件公共接口中使用 CSS 自定义属性有什么好处?
- javascript - Stripe - 如何使用 Checkout Session (php/js) 获取订阅 ID(以取消)