前向T(a)和(T& amp;)(a)之间的区别是什么, [英] what is the difference between forward<T>(a) and (T&&)(a)
问题描述
template<typename T>
void outer(T&& t) {inner(forward<T>(t));}
template<typename T>
void outer(T&& t) {inner((T&&)(t));}
有什么区别?
推荐答案
std :: forward< T>(v)
被指定为 static_cast< T&& 。
There is no practical difference. std::forward<T>(v)
is specified as static_cast<T&&>(v)
.
§20.2.3[forward]
template <class T> T&& forward(typename remove_reference<T>::type& t) noexcept;
template <class T> T&& forward(typename remove_reference<T>::type&& t) noexcept;
2 返回: c> static_cast< T&&>(t)。
2 Returns:
static_cast<T&&>(t)
.
通过大多数C ++风格的cast来确定第一个工作。其中之一是 static_cast
,这也是在这种情况下工作的第一个。
A C-style cast goes through most C++-style casts to determine the first working one. One of them is static_cast
, which also is the first one that works in this case.
§5.4[expr.cast] p4
由
The conversions performed by
- a
const_cast
(5.2.11), - a
static_cast
(5.2.9), - a
static_cast
后跟< $ c> const_cast , - a
reinterpret_cast
(5.2.10),或 - a
reinterpret_cast
后跟const_cast
,
- a
const_cast
(5.2.11), - a
static_cast
(5.2.9), - a
static_cast
followed by aconst_cast
, - a
reinterpret_cast
(5.2.10), or - a
reinterpret_cast
followed by aconst_cast
,
可以使用显式类型转换的cast符号执行。 [...]如果一个转换可以用上面列出的多种方式中的一种来解释,则使用列表中首先出现的解释,即使由该解释产生的转换是错误的。
can be performed using the cast notation of explicit type conversion. [...] If a conversion can be interpreted in more than one of the ways listed above, the interpretation that appears first in the list is used, even if a cast resulting from that interpretation is ill-formed.
但我建议坚持使用 std :: forward
。这个意图从名字上是清楚的,人们会知道它做什么比知道什么奇怪的 static_cast< T&&>
(甚至(T&&)
)。
I'd advise to stick with std::forward
, though. The intent is clear from the name and and people will know what it does much more likely than knowing what a weird static_cast<T&&>
(or even (T&&)
) does.
这篇关于前向T(a)和(T& amp;)(a)之间的区别是什么,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!