The default argument in C ++

I am new to C ++, I have a question about the default argument. If there is a function with the following prototype

void f(int=10,int=20,int=30,int=40) 

If this function is called by passing 2 arguments to it, how can we make sure that these arguments are considered as the first and third, while the second and fourth are accepted as default values.

0
c ++
source share
7 answers

You can not. Arguments of functions correspond to the parameters in order. You can use overloading instead of the default arguments, for example:

 void myFunc(int a,int b,int c,int d); void myFunc(int a,int c) { myFunc(a,20,c,40); } 
+6
source share

It should not be possible. They will be considered as the first two.

You can simply create a function with a different name using two arguments and a call to f .

Alternatively, if you want to emulate named arguments, you can use something similar to smooth interfaces . Example:

 #include <iostream> using namespace std; int f_impl(int a,int b, int c, int d){ cout << a << " " << b << " " << c << " " << d << endl; return 42; } struct f{ int _a, _b, _c, _d; f() : _a(10), _b(20), _c(30), _d(40){} f& a(int a){ _a = a; return *this;} f& b(int b){ _b = b; return *this;} f& c(int c){ _c = c; return *this;} f& d(int d){ _d = d; return *this;} int operator()(){ return f_impl(_a, _b, _c, _d); } }; #define F(x) (f()x()) int main(){ f().a(100).c(300)(); cout << F(.b(1000).d(4000)) << endl; return 0; } 

Output:

 100 20 300 40 10 1000 30 4000 42 
+3
source share

This is not how the default arguments work in C ++. If you pass two arguments to f , they will always be the first two arguments, and the last two will be 30 and 40 .

In other words, C ++ functions only support positional parameters.

+3
source share

As other people say, you cannot do this in C ++.

But you can create a struct / class with four integer members that are initialized with the values ​​you defined. And you pass it as a function parameter.

Example

 struct Param { int a; int b; int c; int d; Param() : a(10), b(20), c(30), d(40) {} void setA(int value) { a = value; } void setB(int value) { a = value; } void setC(int value) { a = value; } void setD(int value) { a = value; } } void f(Param& param) {} Param param; param.setA(67); param.setC(9); f(param); 
+1
source share

The requested function is called 'Named Parameters .

The default parameters and the combined named parameters give you more options to do things as you suggested, but, fortunately, C ++ has no named parameters. However, some other languages, such as C # and VB, and probably Python have named parameters

+1
source share

If necessary, the default arguments will be assigned last.

http://en.wikipedia.org/wiki/Default_argument

0
source share

In fact, you can have named parameters in C ++ with a little help boost :: parameter (also mentioned in the wiki on named parameters).

0
source share

All Articles