Named arguments via struct initialization in functions
Martin Tschierschke via Digitalmars-d
digitalmars-d at puremagic.com
Tue Mar 8 05:52:09 PST 2016
On Sunday, 6 March 2016 at 17:35:38 UTC, Seb wrote:
> Hey all,
>
> I wanted to relive the discussion on named arguments and ping
> for its current status.
>
> There is a bunch of examples to show how needed a unified
> solution for this problem is, let me give you one from phobos
> [2].
>
> ```
> // I want to allow downsizing
> iota(10).sliced!(Yes.replaceArrayWithPointer,
> Yes.allowDownsize)(4);
> ```
>
> There is of course the alternative solution that an author
> overloads his function to the utmost, but this results in
> complexity and duplicated code (see e.g. redBlackTree in phobos
> [3]).
>
> Currently the best solution AFAICT is to use a struct to pass
> such flags, like
>
> ```
> struct Options{int x; int y=1; int z=2;}
> auto fun(Options options)
> {
> return options.x + options.y + options.z;
> }
>
> Options options = {x: 4, z: 3};
> auto a=fun(options);
> ```
>
> There are also other workarounds as discussed in [1] (e.g. with
> CTFE string analysis [4]).
>
> I general there two solutions to this problem
> 1) get true named parameters support in D (probably complicated)
> 2) allow struct inits in functions - e.g. fun({x: 4})
>
> For 2) Jacob Carlborg has proposed something similar three
> years ago. In his case he proposed anonymous structs which
> might be more generally applicable, however just created the
> struct seems easier and allows more
> It doesn't seem that complicated to me as the compiler already
> knows the type of the argument.
>
> Using structs is not ideal, because one can't require
> parameters, but this can be solved by having those parameters
> as normal ones like `sliced(4, {allowDownsize: true})` and it
> creates some maybe unnecessary overhead.
> However it is probably the easiest solution right now.
>
> What are your thoughts on this issue?
>
> On a side note: many templated functions are also complicated
> and experiencing this issue, so it also might be worth to think
> about this issue too ;-)
>
> Cheers,
What about this idea? A new word "as" or something similar.
You have defined:
int fun(int x=100, int y=100, int r=100){...}
int xpos=100;
int ypos=100;
int radius=50;
Now you are allowed to call:
fun(xpos,ypos,radius); // normal nothing has changed!
Call with "as":
fun(ypos as y, xpos as x, radius as r); // different order!
or
fun(radius as r); // defaults values are used.
<=>
fun(,,radius);
The compiler is looking for the right mapping?
More information about the Digitalmars-d
mailing list