mercredi 29 mai 2019

Another question on std::forward: behind the scenes

First of all excuse me for my english very poor and simple.

I'm experimenting with Perfect Forwarding and I found that std::forward needs two overload:

Overload nr. 1:

template <typename T>
inline T&& forward(typename 
std::remove_reference<T>::type& t) noexcept
{
    return static_cast<T&&>(t);
}

Overload nr.2:

template <typename T>
inline T&& forward(typename 
std::remove_reference<T>::type&& t) noexcept
{
    static_assert(!std::is_lvalue_reference<T>::value,
              "Can not forward an rvalue as an lvalue.");
    return static_cast<T&&>(t);
}

Now a typical scenario for Perfect Forwarding is something like

template <typename T1>
void wrapper(T1&& e1)
{
    wrapped(forward<T1>(e1));
}

Of course you know that when wrapper is instantiated, T depends on whether the argument passed to func is an lvalue or an rvalue. If it's an lvalue of type U, T is deduced to U&. If it's an rvalue, T is deduced to U.

In any case - in the scope of wrapper - e1 is an LValue, therefore is always used the first overload of

std::forward

Now my question:

can you show me a valid scenario in which the 2nd overload is used (and is needed)?

Thank you for your time and, again, forgive my english.

Aucun commentaire:

Enregistrer un commentaire