简体   繁体   中英

C++ default function parameter

I want to achieve this:

- second parameter by default set to first argument

Something like:

int foo (int a, int b = a);

But how to do that?

Thanks a lot!

This is forbidden by:

8.3.6 Default arguments [dcl.fct.default]

9) Default arguments are evaluated each time the function is called. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in default argument expressions, even if they are not evaluated. Parameters of a function declared before a default argument expression are in scope and can hide namespace and class member names. [ Example:

int a;

int f(int a , int b = a); / / error: parameter a

/ / used as default argument

typedef int I;

int g( float I , int b = I (2)); / / error: parameter I found

int h(int a , int b = sizeof (a )); / / error, parameter a used

/ / in default argument

—end example ]

An alternative is overloading:

int foo(int a, int b);

int foo(int a)
{
   return foo(a,a);
}

The reason this is disallowed has already been addressed, but another solution along the lines of @Vyktor's is to use boost::optional instead of magic numbers (This has pros and cons compared to creating an overload):

int foo(int a, boost::optional<int> b = boost::none)
{
    if(!b) b = a;
}

I recommend using overloading for this particular task as Luchian Grigore suggested , but common practice would be to reserve some value to say "this is default". For example

int foo( int a, int b = -1)
{
    if( b == -1){
       b = a;
    }
}

Using object (not scalar values) this could be really nicely implemented (by creating new delivered class reserved to represent default value), but with int you have to do this.

Note that you have to be 100% sure that b cannot get value -1 (or whatever your reserved value is).

This is a little funny answer - but works:

#define TWO_FROM_ONE(a) (a),(a)

f(TWO_FROM_ONE(12));

One disadvantage is that this will call some function twice (a known macro drawback):

f(TWO_FROM_ONE(sin(123 / PI)));

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