Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore reference function argument

I have function with this signature (I can not edit it):

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

I want to call it but I do not care about the getting c. Currently I do this:

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

My solution seems dumb. What is the standard way to ignore this argument.

like image 764
Humam Helfawi Avatar asked Jan 19 '16 07:01

Humam Helfawi


3 Answers

There is none.

If your main concern is about polluting the current stack with a temp variable, a wrapper function like this should suffice:

void foo_wrapper(int a, int b)
{
    int temp; foo(a, b, temp);
}
like image 53
Fox Avatar answered Oct 20 '22 17:10

Fox


I would write an overload that turns the output argument into a normal return value. I really don't like output arguments and think that they should be avoided.

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

In your program, you just this overload and either ignore the return value or use it.

like image 35
Jens Avatar answered Oct 20 '22 16:10

Jens


This is an over engineered solution, so I don't actually recommend it as the first option in production code.

You can create a class to help you easily ignore these kinds of arguments:


template <class T>
struct RefIgnore
{
    static inline T ignored_{};

    constexpr operator T&() const
    {
        return ignored_;
    }
};

template <class T>
constexpr RefIgnore<T> ref_ignore{};
void foo(int a,int b, int& c);

auto test()
{
    foo(2, 3, ref_ignore<int>);
}
like image 29
bolov Avatar answered Oct 20 '22 16:10

bolov