Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass only a few default parameters?

I created a function like:

void triangle(int n, int start=1, int spcs=0, char dec_y='n', char lf='#',char decf='o') {
    //some code
}

I wanted to know is there any way that I could call this function like this:

triangle(9, dec_y='y', lf='&');

without doing this:

void triangle2(int nn, char d_ec_y, char llf) {
    triangle(nn, 1, 0, d_ec_y, llf, 'o');
}
// then in main simply
triangle2(9, 'y', '&');
like image 873
xypnox Avatar asked Sep 14 '25 22:09

xypnox


1 Answers

You can't change the order of the parameters. So you can't do what you want directly. You have three options:

  • One that you don't want to.
  • You can pass the parameters as structure. The struct can have default values. And you can only alter the ones which you want before calling the function.

For example:

struct params
{
    params(int n_)
     :n(n_)
    {
    }
    int start=1;
    int spcs=0; 
    char dec_y='n';
    char lf='#';
    char decf='o';
};

...
params p(0);
p.dec_y='y';
p.lf='&';
triangle(p);
  • You can use boost::parameter which provides exactly what you want. Check this question for a sample usage.
like image 101
seleciii44 Avatar answered Sep 16 '25 14:09

seleciii44