具有参考参数的C ++函数适用于左值和右值 [英] C++ function with reference argument that works for lvalues and rvalues

查看:70
本文介绍了具有参考参数的C ++函数适用于左值和右值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有一个C ++函数,该函数带有一个参数,这是一个引用,并且可以使用相同的语法来同时处理左值和右值.

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.

以这个例子为例:

#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 (一个右值).我希望我的函数的语法可以很好地处理,而无需重复任何代码.

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.

谢谢!

推荐答案

这是

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.

转发引用是一种特殊的引用,可以保留函数自变量的值类别,使其有可能通过 std :: forward 转发

例如

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

这篇关于具有参考参数的C ++函数适用于左值和右值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆