C++ function with reference argument that works for lvalues and rvalues
C++ function with reference argument that works for lvalues and rvalues
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.
n
3
Thank you!
1 Answer
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
.
std::forward
e.g.
template <typename T>
void triple_value(T &&n)
n *= 3;
cout << "Inside function: " << n << endl;
std::forward
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
note that in a real life scenario you will probably need to use
std::forward
somewhere in that function– Ap31
Sep 11 '18 at 6:01