C++ function with reference argument that works for lvalues and rvalues

孤街醉人 提交于 2019-12-11 03:43:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!