Key arguments
Bill Baxter
dnewsgroup at billbaxter.com
Mon Jul 14 16:36:16 PDT 2008
baleog wrote:
> How can i implement key arguments in D? I want something like this:
> --
> void f(int x, double y = 2.0, int z = 3);
> ...
> f(1, z:10, y:5.1); // x=1, y=5.1, z=10
> f(1, z:10); // x=1, y=2.0, z=10
> --
> I tried to do this with Variant type and explicit type checking. But it takes a lot of routine actions. Maybe exists a better way?
>
> Best regards
If you have a lot of arguments with various optional arguments that each
have their own defaults, I think a struct is the most straightforward
solution right now.
struct FOptions {
double y = 2.0;
int z = 3;
}
void f(int x, FOptions opt) {...}
{FOptions opt;
opt.z = 10;
opt.y = 5.1;
f(1, opt);
}
{FOptions opt;
opt.z = 10;
f(1, opt);
}
It would be a lot nicer if static struct initializers worked for
non-static structs too. Then you could do:
Foptions opt = {z:10};
f(1,opt);
Or even f(1,{z:10});
There have been proposals to make struct initializers more useful along
these lines. The next step logical step in that evolution would be to
recognize a trailing struct argument as a keyword set, and let you call
f(1,z:10)
as a shortcut for
f(1,{z:10})
which would be a shortcut for something like
f(1,cast(FOptions){z:10})
which would work if struct initializers didn't have to be static.
Walter doesn't seem particularly interested, though.
--bb
More information about the Digitalmars-d-learn
mailing list