![](/img/trans.png)
[英]Why do we need a template specialization for a template-template parameter
[英]Why do we need second std::forward specialization?
据我从对std::forward
如何工作的解释中了解到的http://thbecker.net/articles/rvalue_references/section_08.html,我们只能省去std::forward
一个版本:
template<class S>
S&& forward(typename remove_reference<S>::type& a) noexcept
但实际上,我们有( http://en.cppreference.com/w/cpp/utility/forward )第二个版本:
template< class T >
T&& forward( typename std::remove_reference<T>::type&& t );
与前一个不同之处仅在于如何定义t
(使用&&
)
那么,为什么我们需要它呢? 如果将其拆下会怎样?
std::forward
重载的参数(使用std::remove_reference
)会删除所有否则会发生的引用折叠和参数推导,并强制将lvalue和rvalue引用绑定到正确的重载。 无需添加或删除原始参数T
一部分(或不包含)的任何可能的const
即可完成此操作(即,我们不使用const T&
因为它本质上将const
添加到T&&
尚未添加的右值中)它们都可以绑定到同一个右值)。
在右值引用重载中执行关键错误检查 ; 确保提供rvalue时不调用std::forward
转发给左值引用是一项健全的检查; 基本上确保类似std::forward<int&>(42);
无法编译。 std::forward
打算在公式std::forward<T>
,其中T
来自于推导上下文T&&
如参考文献中所述。 过载会产生与条件返回相同的结果,并且需要进行错误检查。
std::forward
的实现适用于Scott Meyers在“ Going Native 2013”演讲中谈到的“有条件强制转换”。 Scott Meyers在其演示文稿中提供了以下伪代码,以解释std::forward
的工作原理(大约20分钟标记);
template <typename T>
T&& forward(T&& param) { // T&& here is formulated to disallow type deduction
if (is_lvalue_reference<T>::value) {
return param; // return type T&& collapses to T& in this case
}
else {
return move(param); // return type is T&&
}
}
std::forward
的实参类型为左值,则实现为返回左值引用;如果其实参类型为右值,则返回右值引用(与std::move
等效)。
TL; DR 为什么需要它? 基本上; 它可以防止对std::forward
错误使用(例如,悬空引用,对临时对象的引用不再可用,修改/修改的文字等)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.