1
votes

The std::forward function template returns T&&. So in order to forward its argument as either an lvalue reference or an rvalue reference, the return type of std::forward must be:

T&& if T is a non-reference type (T && == T&&)
T& if T is an lvalue reference type (T& && == T&)

What I mean is do std::forward's return type changes due to the reference-collapsing rules or the explanation is different?

Is the return type of std::forward a forwarding (universal) reference?

2

2 Answers

1
votes

The answer is yes. The reference collapsing rules, as stated in [dec.ref]/6, do not differentiate between the type of a variable, the type of a function parameter, or the return type of a function.

0
votes

It depends on the context. If the type is somehow deduced (template context), it will work:

int a;
template <typename T>
T&& foo()
{
    return a;
}

on the other hand, it will not work when the type is not deduced:

int a;
int&& bar()
{
    return static_cast<int&>(a); // error: binding l-value to r-value reference
}

Like L Shau pointed out, you can find the rule in the standard.