c++ - Why I cannot use previous argument values to define argument default values? -
for example, why cannot write this:
void f(double x, double y = x);
to declare function f
, call f(x)
equivalent f(x,x)
?
in case doesn't seem useful you, here's possible usage scenario. in example, declare f
follows:
void f(double x, double y = expensivecomputation(x));
where expensivecomputation
denotes, guessed it, function slow computation. want give user of f
possibility of passing in value of y
if has computed previously, don't have compute again inside f
. now, of course can resolve writing 2 overloads:
void f(double x, double y); void f(double x) { f(x, expensivecomputation(x)); }
but writing overloads becomes tiresome number of arguments grows. example, try 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 uglier. default arguments sexy. there deeper syntactic reason why previous arguments can't used define argument default values?
i don't know why default argument can't go way, maybe can try wrap arguments in struct(class)?
struct paramset { double x; double p; double q; paramset(double x) : x(x) , p(expensivecompute1(x)) , q(expensivecompute2(x, p)) { } paramset(double x, double p) : x(x) , p(p) , q(expensivecompute2(x, p)) { } paramset(double x, double p, double q) : x(x), p(p), q(q) { } private: double expensivecompute1(double x) {} double expensivecompute2(double x, double p) {} }; void f(paramset ps);
still need ctor overloads, no more works writing expensivecomputation()
series provided, , @ least things wrapped in struct
also, signature of f()
fixed, , there 1 version.
Comments
Post a Comment