简体   繁体   中英

How to set a preceding function parameter to its default in c++?

Apologies if this basic question has already been answered. What would I put inside the brackets of print() so that the first parameter is left to the default value but the following parameters are given new values of 1 and 2? I know I can literally put 0 in there but is there a way for it go to a default?

#include<iostream>

using namespace std;

void printer(int a=0, int b=0, int c=0){
 cout << a << endl;
 cout << b << endl;
 cout << c << endl;
}

int main(){

//leave a=0 and replace both b and c 
printer(/*?*/,1,2);

 return 0;
}

You cannot do that, it's not allowed. Only right most parameters could be omitted.

Default parameter list is right associative. So its not possible to ommit first parameter list.

all parameters after first default are default. You can get what you want in this particular case changing the sequence:

void printer(int b=0, int c=0,int a=0){
 cout << a << endl;
 cout << b << endl;
 cout << c << endl;
}

//leave a=0 and replace both b and c 
printer(1,2);

output:

0

1

2

Use std::placeholders::N to delegate the arguments to specify to the returned function object from std::bind .

int main()
{
   auto f = std::bind(printer, 0, std::placeholders::_1, std::placeholders::_2);

   f(4, 5);
}

Live Demo

You could utilize function overloading to achieve what you want:

void printer(int a, int b, int c) {
  cout << a << endl;
  cout << b << endl;
  cout << c << endl;
}

void printer() {
  printer(0, 0, 0);
}

void printer(int b = 0, int c = 0) {
  printer(0, b, c);
}

int main(){
  // leave a = 0 and replace both b and c 
  printer(1, 2);

  return 0;
}

You can't do exactly that, but one approach to this problem is to pass a struct with your parameters:

struct PrinterParams {
  int a,b,c;
  PrinterParams() : a(0), b(0), c(0) { }
};

void printer(int a, int b, int c) {
 cout << a << endl;
 cout << b << endl;
 cout << c << endl;
}

void printer(const PrinterParams &params) {
  printer(params.a,params.b,params.c);
}


int main(){
  PrinterParams params;

  params.b = 1;
  params.c = 2;
  printer(params);

 return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM