在函数模板中,需要完全依照模板的参数类型(即保持参数的左值、右值特征),将参数传递给函数模板中调用的另外一个函数。c++11提供了这样的一个函数std::forward,不管参数是T&&这种未定的引用,还是明确的左值引用或右值引用,它会按照参数本来的类型转发。
forward会把左值传递给右值。
struct A {
int value;
explicit A(int value) : value(value) {
std::cout << "constructor" << std::endl;
}
~A() {
std::cout << "destructor" << std::endl;
}
};
void test(A&& a, double b) {
std::cout << a.value << " " << b << std::endl;
}
template <class... Args>
void test_forward(Args&... args) {
test(std::forward<Args>(args)...);
}
A a(1);
float b = 2.1;
test_forward(a, b);
a.value = 2;
test_forward(a, b);
constructor
1 2.1
2 2.1
destructor