dimanche 26 février 2017

How do two overloaded std::forward work?

I have found in std library the following implementation of std::forward:

// TEMPLATE FUNCTION forward
template<class _Ty> inline
constexpr _Ty&& forward(
    typename remove_reference<_Ty>::type& _Arg) _NOEXCEPT
{   // forward an lvalue as either an lvalue or an rvalue
return (static_cast<_Ty&&>(_Arg));
}

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

First function works obviously, but for second I cannot find usefull example. If I try to do something like this:

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

template<typename T>
T getRValue()
{
    return std::remove_reference<T>::type{};
}

template<typename T>
void setValue(T && i)
{
   my_forward<T>(getRValue<T>());
}

int main()
{
    int i = 1;
    setValue(i);
}

to check when second function is called, I have got the error:

Error   C2664   '_Ty my_forward<T>(int &&) noexcept': cannot convert argument 1 from 'int' to 'int &&'

Does anybody know in which case second overloaded function (in my terms my_forward) is called ? Or may be some good example for it ? By the way my compiler is MSVC 2015

Thanks, all for help !!

Aucun commentaire:

Enregistrer un commentaire