For example, why I cannot write this:
void f(double x, double y = x);
to declare a function f
, for which the call f(x)
is equivalent to f(x,x)
?
In case this doesn't seem useful to you, here's a possible usage scenario. In this example, I declare f
as follows:
void f(double x, double y = expensiveComputation(x));
where expensiveComputation
denotes, you guessed it, a function that does a very slow computation. I want to give the user of f
the possibility of passing in the value of y
if he has computed it previously, so I don't have to compute it again inside f
. Now, of course I can also resolve this by writing two overloads:
void f(double x, double y);
void f(double x) { f(x, expensiveComputation(x)); }
but writing overloads becomes tiresome as the number of arguments grows. For example, try to write:
void f(double x, double p = expensiveComputation(x),
double q = expensiveComputation2(x, p),
double r = expensiveComputation3(x, p, q),
double s = expensiveComputation3(x, p, q, r));
using overloads. It's just uglier. Default arguments are sexy. Is there a deeper syntactic reason why previous arguments can't be used to define argument default values?