我想要一个 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);
}
Output:
Inside function: 9
Outside function: 9
Inside function: 15
这段代码有效。但我的案例需要两个不同的函数,第一个函数是我通过的n
(左值)和3
(右值)。我希望我的函数的语法能够很好地处理两者,而不需要重复任何代码。
谢谢你!
这是什么转发参考 https://en.cppreference.com/w/cpp/language/reference#Forwarding_references应该做的。它可以与左值和右值一起使用,并保留函数参数的值类别。
转发引用是一种特殊的引用,它保留
函数参数的值类别,使得可以
通过以下方式转发std::forward https://en.cppreference.com/w/cpp/utility/forward.
e.g.
template <typename T>
void triple_value(T &&n) {
n *= 3;
cout << "Inside function: " << n << endl;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)