Home > front end >  How can we declare lvalue inplace while calling a function with lvalue reference parameter?
How can we declare lvalue inplace while calling a function with lvalue reference parameter?

Time:11-17

If I have a function like this:

int calc(const DataVec& data_vec, int& sub_sum);

how can I call that without a explicit lvalue definition of type int?

auto calc_result = calc(data_vec, int()); // error, int() is not a lvalue

Below is a valid form:

int _;  // not interested
auto calc_result = calc(data_vec, _);

CodePudding user response:

This can be solved with function overloading. Like

int calc(const DataVec& data_vec);

Your overloaded function could be a simple wrapper around your dummy-int variable workaround:

int calc(const DataVec& data_vec)
{
    int dummy = 0;
    return calc(data_vec, dummy);
}

Please note that this might be a suitable workaround to the problem. But it might as well be a workaround for a problem that doesn't really exist. Perhaps there is a very good reason for the original calc functions second argument being a non-const lvalue reference?

  •  Tags:  
  • c
  • Related