忽略参考函数自变量

问题描述 投票:3回答:3

我具有此签名的功能(我无法编辑):

void foo(int a,int b, int& c);

我想称呼它,但我不在乎得到c。目前,我正在这样做:

int temp;
foo(5,4,temp);
//temp never used again

我的解决方案似乎很愚蠢。忽略此参数的标准方法是什么。

c++ c++11 parameter-passing
3个回答
6
投票

没有。

如果您的关注主要是由于存在temp而污染当前堆栈,则包装函数...如:

void foo_wrapper(int a, int b)
{
    int temp; foo(a, b, temp);
}

应该足够。


4
投票

我会写一个重载,将输出参数转换为正常的返回值。我真的不喜欢输出参数,并认为应该避免使用它们。

int foo(int a, int b) {
    int tmp = 0;
    foo(a,b, tmp);
    return tmp;
}

在您的程序中,您只是这个重载而忽略了返回值或使用它。


-2
投票

代替引用,您可以将其作为指针传递

void foo(int a,int b, int *c = NULL);

在呼叫位置,您可以将其设为

foo(5, 6);

或者如果您想传递第三个参数,则可以将其设为

int n = 3; foo (1, 2, &n);

© www.soinside.com 2019 - 2024. All rights reserved.