Named arguments via struct initialization in functions

Seb via Digitalmars-d digitalmars-d at puremagic.com
Sun Mar 6 09:35:38 PST 2016


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,

Seb

[1] 
http://forum.dlang.org/post/pxndhoskpjxvnoacajaz@forum.dlang.org
[2] https://github.com/DlangScience/mir/issues/18
[3] 
https://github.com/D-Programming-Language/phobos/pull/4041/files
[4] 
https://github.com/timotheecour/dtools/blob/master/dtools/util/functional.d


More information about the Digitalmars-d mailing list