I'd appreciate your help understanding std::forward implementation.
What's the difference between std::forward and a standard cast to T&& in a template function? In this example at least, they both seem to do the forwarding work correctly. The LValue gets forwarded to the LValue overload, and the RValue is forwarded to the RValue overload.
struct DemoPerfectForwardVsRefRefCast
{
void overloaded(int const &arg) { std::cout << "receive by lvalue\n"; }
void overloaded(int && arg) { std::cout << "receive by rvalue\n"; }
template< typename t >
void forwarding(t && arg) {
std::cout << "via std::forward: ";
overloaded(std::forward< t >(arg)); // forwards correctly
std::cout << "via && cast: ";
overloaded(static_cast<t&&>(arg)); // seems to also forward correctly
}
void demo()
{
std::cout << "initial caller passes rvalue:\n";
forwarding(5);
std::cout << "initial caller passes lvalue:\n";
int x = 5;
forwarding(x);
}
};
Is universal reference + reference collapsing + static cast to T&& enough?
In Visual Studio 2017 the definition of std::forward is implemented differently, with two template functions, one with a T& param, and one with a T&& param. Is that necessary? Is it better than just the cast?
std::forward<T>(x)asstatic_cast<T&&>(x). - HTNW