问题
I would like to have a C++ function which takes an argument, that's a reference, and works for both lvalues and rvalues with the same syntax.
Take this example:
#include <iostream>
using namespace std;
void triple_lvalue(int &n) {
n *= 3;
cout << "Inside function: " << n << endl;
}
void triple_rvalue(int &&n) {
n *= 3;
cout << "Inside function: " << n << endl;
}
int main() {
int n = 3;
triple_lvalue(n);
cout << "Outside function: " << n << endl;
triple_rvalue(5);
}
Output:
Inside function: 9
Outside function: 9
Inside function: 15
This code works. But I need two different functions for my cases, the first where I pass n
(an lvalue) and 3
(an rvalue). I would like syntax for my function that handles both just fine, without needing to repeat any code.
Thank you!
回答1:
This is what forwarding reference supposed to do. It could be used with both lvalues and rvalues, and preserves the value category of the function argument.
Forwarding references are a special kind of references that preserve the value category of a function argument, making it possible to forward it by means of std::forward.
e.g.
template <typename T>
void triple_value(T &&n) {
n *= 3;
cout << "Inside function: " << n << endl;
}
来源:https://stackoverflow.com/questions/52269498/c-function-with-reference-argument-that-works-for-lvalues-and-rvalues