The origin of C + + forward keyword forward: The derivation type in the template function, as the parameter of the function, that is, the use of t&& Arg to declare, after the derivation of the specific type, can not be deduced after the specific type, converted to Rvalue reference. Forward is to solve this problem.
forward() 函数的作用:它接受一个参数,然后返回该参数本来所对应的类型的引用。
The following example is not able to invoke the
void rvalue_call(int&& v)
void rvalue_call(const int&& v)
include <iostream>using namespace std;void rvalue_call(int& v){ cout << "& call" << endl;}void rvalue_call(int&& v){ cout << "&& call" << endl;}void rvalue_call(const int& v){ cout << "const & call" << endl;}void rvalue_call(const int&& v){ cout << "const && call" << endl;}template<typename T>void func(T&& a){ rvalue_call(a);}int main(void){ int x = 1; func(x);//实参为左值 int& y = x; func(y);//实参为左值引用 func(std::move(y));//实参为右值引用 func(100);//实参为右值引用 const int a = 11; func(a);//实参为左值常引用 func(std::move(a));//实参为右值常引用 }
Workaround: Add Std::forward
#include <iostream>using namespace std;void rvalue_call(int& v){ cout << "& call" << endl;}void rvalue_call(int&& v){ cout << "&& call" << endl;}void rvalue_call(const int& v){ cout << "const & call" << endl;}void rvalue_call(const int&& v){ cout << "const && call" << endl;}template<typename T>void func(T&& a){ rvalue_call(std::forward<T> (a));}int main(void){ int x = 1; func(x);//实参为左值 int& y = x; func(y);//实参为左值引用 func(std::move(y));//实参为右值引用 func(100); const int a = 11; func(a); func(std::move(a));}
C + + rvalue reference, forward keyword