Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Supply second optional argument without need to suply first optional argument?

I have a function like this:

 void foo(int optionalinteger=0, float optionalfloat=0.0f, cell *optionalarray=NULL)
 {
          return;
 }

I tried to acces an optional argument like

 foo(.optionalfloat=5.5f); // from another programming language

but that gives an error. How do I access only the optional value I choose to without the need to supply other optional values?


2 Answers

Depending on your needs, you could overload the foo() function.

void foo(int optionalinteger=0, float optionalfloat=0.0f, cell *optionalarray=NULL)
{
    return;
}

void foo( float optionalfloat )
{
    foo( 0, optionalfloat, NULL );
}

This solution is of course limited as it will not work in all situations. If given the following method

void foo(int optlint=0, float optflt1=0.0f, float optflt2=0.0f, cell *optionalarray=NULL)
{
    return;
}

It would not be possible to create individual overloaded functions for both float parameters.

like image 155
ctor Avatar answered Mar 13 '26 10:03

ctor


If you really want to, you can use something akin to the named parameter idiom, e.g.:

struct cell;

void foo(int optionalinteger, float optionalfloat, cell *optionalarray) {}

struct foo_params {
  foo_params& integer(int v) { integer_ = v; return *this; }
  foo_params& fl(float v) { fl_ = v; return *this; }
  foo_params& array(cell *v) { array_ = v; return *this; }

  // C++11 defaults for laziness, easy to change though
  int integer_=0;
  float fl_=0.0f;
  cell *array_=nullptr;
};

void foo(foo_params params = foo_params()) {
  foo(params.integer_, params.fl_, params.array_);
}

int main() {
  foo(foo_params().integer(100)
                  .array(0));
}

That's quite a lot of work for something quite simple and counter-intuitive if you're not really expecting to see something like that in your code base.

Or you could use the boost named parameter library if you prefer.

like image 28
Flexo Avatar answered Mar 13 '26 08:03

Flexo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!