I'm experimenting with Perfect Forwarding and I found that
std::forward()
needs two overloads:
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 T>
void wrapper(T&& e)
{
wrapped(forward<T>(e));
}
Of course you know that when wrapper()
is instantiated, T
depends on whether the argument passed to it 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()
- e
is an lvalue, therefore it always uses the first overload of std::forward()
.
Now my question:
What is a valid scenario in which the 2nd overload is used (and is needed)?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…