为什么我应该显式地将typename传递给std::forward

Why should I explicitly pass typename to std::forward?

本文关键字:std forward typename 我应该 为什么      更新时间:2024-09-26

为什么需要在std::forward中显式指示模板参数的类型?

template <class T> void foo (T&& x) {
goo (x);                   // always an lvalue
goo (std::forward<T>(x));  // rvalue if argument is rvalue
}

考虑std::正向实现

template <typename T>
T&& forward(std::remove_reference_t<T>& x)
{
return static_cast<T&&>(x);
}

std::remove_reference实现

template< class T > struct remove_reference      {typedef T type;};
template< class T > struct remove_reference<T&>  {typedef T type;};
template< class T >
using remove_reference_t = typename remove_reference<T>::type;

std::forward()中的参数类型为:

remove_reference<T>::type

这里T位置是作用域分辨率运算符::的左边;非推导上下文";(请参阅cpprreference上的非推导上下文(。因为它不是自动推导出来的,所以您必须自己提供类型。