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

Viewed 62

Why is it necessary to explicitly indicate the type of template argument in std::forward?

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

considering std::forward implementation:

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

and std::remove_reference implementation:

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;
1 Answers

The argument's type in std::forward() is:

remove_reference<T>::type

Here T position is left of the scope resolution operator ::, which makes it a "non-deduced context" (see non-deduced context on cppreference). Because it is not automatically deduced, you have to provide the type yourself.

Related