在 move.h 中,forward
有两个重载
template<typename _Tp>
constexpr _Tp&&
forward(typename std::remove_reference<_Tp>::type& __t) noexcept
{
return static_cast<_Tp&&>(__t);
}
template<typename _Tp>
constexpr _Tp&&
forward(typename std::remove_reference<_Tp>::type&& __t) noexcept
{
static_assert(
!std::is_lvalue_reference<_Tp>::value,
"template argument substituting _Tp is an lvalue reference type"
);
return static_cast<_Tp&&>(__t);
}
我看到 static_assert
是为了防止意外地将右值转换为左值。右值版本可以这样实现吗:
template<typename _Tp>
typename std::remove_reference<_Tp>::type&&
forward(typename std::remove_reference<_Tp>::type&& __t) noexcept
{
return __t;
}
最佳答案
关于为什么将右值作为左值转发是危险的示例,请参见 N2951 的用例 C .这个用例展示了这样做如何使创建悬挂引用变得容易。
关于c++11:为什么 std::forward 中的 static_assert 是必需的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10335916/