Some functions need to forward one or more arguments along with the type to other functions, in which case we need to maintain all the properties of the forwarded argument, including whether the argument type is const and if the argument is an lvalue or an rvalue.
Template <typename F, TypeName T1, TypeName t2>void func (f F, T1 T1, T2 T2) { f (T2, T1);} void subfunc (intint &v2) { + +v2;} int 0 2); // I did not increase
We can use rvalue references to solve these problems:
Template <typename F, TypeName T1, TypeName t2>void func (f F, T1 &&t1, T2 &&T2) { F ( T2, T1);} void subfunc (intint &v2) { + +v2;} int 0 2); // I added, and can also pass the const
But the function func works well for a function that accepts an lvalue reference, but does not accept the function of an rvalue reference parameter:
Template <typename F, TypeName T1, TypeName t2>void func (f F, T1 &&t1, T2 &&T2) { F ( T2, T1);} void subfunc (intint &v2) { + +v2;} int 0 2); // error, cannot instantiate from an lvalue int&&
To solve these problems, we can use a new standard library called forward to pass the parameters, which preserves the type of the original argument. Forward must be called by displaying template arguments. Forward returns an rvalue reference for the display argument type.
Template <typename F, TypeName T1, TypeName t2>void func (f F, T1 &&t1, T2 &&T2) { F ( Std::forward<T2> (T2), std::forward<t1> (t1)); // by reference collapse, lvalue or lvalue, right or right value }void subfunc (intint &v2) { + +v2;} int 0 2); // correct
C + + Primer notes--forwarding