Key arguments

downs default_357-line at yahoo.de
Mon Jul 14 08:51:17 PDT 2008


Jarrett Billingsley wrote:
> > "baleog" <maccarka at yahoo.com> wrote in message
> > news:g5er1d$1p15$1 at digitalmars.com...
>> >> 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
> >
> > Downs will reply with a horrid hack involving overloading opAssign for some
> > static instances of some structures and then getting their values in the
> > function, but then you're severely limited since the "parameter" names are
> > globals, and since that's so, you can't have two functions that use the same
> > named parameters executing at the same time, either in a multithreaded
> > fashion or with simple recursion.
> >

Such abject nonsense. My hack is based on typesystem abuse, not global *variables*.
It also doesn't use structs.

Basically, the idea is that you typedef double y_parameter; then y_parameter y_p(double d) { return cast(y_parameter) d; }

Then just make f a templated function, so that void f(T...)(int x, T t); and check for the presence of a y_parameter in T.

Called like so: f(2, y_p = 5f);


More information about the Digitalmars-d-learn mailing list