c-forward(a)和(T \u0026\u0026)(a)有什么区别

template<typename T>  
void outer(T&& t) {inner(forward<T>(t));}  

template<typename T>  
void outer(T&& t) {inner((T&&)(t));}  


没有实际的区别. std :: forwardT(v)被指定为static_cast< T&>(v).


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 Returns: static_cast<T&&>(t).


§5.4[expr.cast] p4

The conversions performed by

  • a const_cast (5.2.11),
  • a static_cast (5.2.9),
  • a static_cast followed by a const_cast,
  • a reinterpret_cast (5.2.10), or
  • a reinterpret_cast followed by a const_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&)).

转载注明原文:c-forward(a)和(T \u0026\u0026)(a)有什么区别 - 代码日志