【发布时间】:2018-09-11 05:56:37
【问题描述】:
我想要一个 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(右值)。我希望我的函数的语法能够很好地处理这两种情况,而无需重复任何代码。
谢谢!
【问题讨论】:
标签: c++ function reference rvalue lvalue