Allow struct constructors with all parameters optional

Ogi ogion.art at gmail.com
Wed Aug 28 07:52:49 UTC 2024


On Tuesday, 27 August 2024 at 22:53:45 UTC, IchorDev wrote:
> I can’t remember exactly what the reasons for that were, but I 
> thought those reasons applied equally to any constructors that 
> *could* be called with 0 parameters?


The reasons are that, AFAIK, language designers decided that `S 
s` and `auto s = S()` producing different results would be too 
confusing.

Speaking of constructors that could be called with zero 
parameters. All kinds of variadic constructors are perfectly 
fine, despite the fact that regular variadic functions can be 
called with zero parameters:

```D
struct A {
     this(Args...)(Args) { writeln("ctor"); }
}
  struct B {
     this(...) { writeln("ctor"); }
}
struct C {
     this(int[]...) { writeln("ctor"); }
}
struct D {
     this(Object...) { writeln("ctor"); }
}
```

All these structs are default-initialized with zero arguments and 
call their constructor with non-zero number of arguments. Exactly 
how I expect a constructor with all optional parameters to behave.

> Could you also elaborate about how named parameters affect this 
> situation?

Consider this function:
```
void fun(int a = 0, int b = 0, int c = 0)
```
Before introduction of named arguments it wasn’t possible to call 
`fun` by only passing `c`. You had to pass all preceding 
arguments as well: `fun(0, 0, 42)`. So even if you could define a 
struct constructor with all optional parameters, this wouldn’t 
make any difference. You always had to pass at least the first 
argument anyway.

Nowadays, thanks to named arguments, you actually can call `fun` 
by only passing `c`: `fun(c:42)`. With this change struct 
constructors with all optional parameters became useful, but they 
are still prohibited.


More information about the dip.ideas mailing list