Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement a forward function using universal reference

Tags:

c++

c++11

The implementation of std::forward in VS2013 is

template<class _Ty> inline
    _Ty&& forward(typename remove_reference<_Ty>::type& _Arg)
    {   // forward an lvalue
    return (static_cast<_Ty&&>(_Arg));
    }

template<class _Ty> inline
    _Ty&& forward(typename remove_reference<_Ty>::type&& _Arg) _NOEXCEPT
    {   // forward anything
    static_assert(!is_lvalue_reference<_Ty>::value, "bad forward call");
    return (static_cast<_Ty&&>(_Arg));
    }

One version for lvalue reference, one version for rvalue reference. Why not just use a universal reference for both rvalue and lvalue reference:

template <typename T, typename U>
T&& Forward(U&& arg) {
  return static_cast<T&&>(arg);
}
like image 234
QingYun Avatar asked May 04 '26 01:05

QingYun


1 Answers

Your version is not standard-compliant, as std::forward is is required to not compile when called with on an rvalue if T is an l-value reference. From [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 Returns: static_cast<T&&>(t).

3 if the second form is instantiated with an lvalue reference type, the program is ill-formed.

std::forward is defined in this way to ensure that (some) misuses of std::forward do not compile. See n2951 for more discussion (although even n2951 does not use this exact form).

like image 139
Mankarse Avatar answered May 05 '26 15:05

Mankarse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!