Caduchon
Caduchon

Reputation: 5211

Interface a function to have an optional argument instead of a required one

Suppose I use a function (coming from a third-party API, in another namespace) having arguments filled by the function with some information:

double foo::f(double x, double& info);

When I call it, I have to create a local variable, even if I don't care about the filled value:

const double x = 3.14159;
double info = 0.0;
const double y = foo::f(x, info);
// Nothing to do with info

Then, I want to interface this function to have an optional argument instead of a reference. Is there an usual/better/easiest/more-readable way than the following to do that ?

double ff(double x, double* info = 0)
{
  double unused_info = 0.0;
  double& info_ = ((bool)info ? *info : unused_info);
  return foo::f(x, info_);
}

This works, but it looks a little bit clumsy for the need.

Note: I don't use C++11 for compatibility reasons. But I'm interested by C++11 solutions even if it doesn't answer the question.

Upvotes: 1

Views: 135

Answers (1)

Paul R
Paul R

Reputation: 212979

Rather than change the current implementation you can just add an overloaded function with one argument:

double f(double x)
{
    double info;
    return f(x, info);
}

Upvotes: 5

Related Questions