Possible Duplicate:
What are the main purposes of std::forward and which problems does it solve?
I know what it does and when to use it but I still can't wrap my head around how it works. Please be as detailed as possible and explain when std::forward
would be incorrect if it was allowed to use template argument deduction.
Part of my confusion is this:
"If it has a name, it's an lvalue" - if that's the case why does std::forward
behave differently when I pass thing&& x
vs thing& x
?
First, let's take a look at what
std::forward
does according to the standard:ยง20.2.3 [forward] p2
(Where
T
is the explicitly specified template parameter andt
is the passed argument.)Now remember the reference collapsing rules:
(Shamelessly stolen from this answer.)
And then let's take a look at a class that wants to employ perfect forwarding:
And now an example invocation:
I hope this step-by-step answer helps you and others understand just how
std::forward
works.