具有适用于左值和右值的引用参数的 C++ 函数

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

我想要一个 C++ 函数,它接受一个参数,它是一个引用,并且适用于具有相同语法的左值和右值

举个例子:

#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);
}

输出:

Inside function: 9
Outside function: 9
Inside function: 15

此代码有效。但是我的案例需要两个不同的函数,第一个是我传递 n (左值)和 3 (右值)的地方。我希望我的函数的语法能够很好地处理这两种情况,而无需重复任何代码。

谢谢!

这就是 forwarding reference 应该做的。它可以与左值和右值一起使用,并保留函数参数的值类别。

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.

例如

template <typename T>
void triple_value(T &&n) {
  n *= 3;
  cout << "Inside function: " << n << endl;
}