C ++ default function parameter

I want to achieve this:

- second parameter by default set to first argument 

Sort of:

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

But how to do that?

Thanks a lot!

+6
source share
4 answers

It is forbidden:

Arguments

8.3.6 Default [dcl.fct.default]

9) By default, arguments are evaluated each time the function is called. The evaluation order of the function arguments is not specified. Therefore, function parameters should not be used as default arguments, even if they are not evaluated. Parameters A function declared before the default argument expression in a scope and can hide namespace names 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]

Alternative overload:

 int foo(int a, int b); int foo(int a) { return foo(a,a); } 
+18
source

The reason why this is forbidden has already been considered, but another solution like @Vyktor is to use boost::optional instead of magic numbers (this has pros and cons compared to creating overloads):

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

I recommend using overloading for this particular task, as suggested by Lucian Grigore , but it would be common practice to reserve some value to say โ€œthis is the default valueโ€. for instance

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

Using an object (not scalar values), this can be really well implemented (by creating a new class reserved for representing the default value), but with int you have to do it.

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

+2
source

This is a bit ridiculous answer - but it works:

 #define TWO_FROM_ONE(a) (a),(a) f(TWO_FROM_ONE(12)); 

One of the drawbacks is that it will call some function twice (a known macro flaw):

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

Source: https://habr.com/ru/post/927501/


All Articles