Allow struct constructors with all parameters optional

Ogi ogion.art at gmail.com
Tue Aug 27 08:48:19 UTC 2024


It is valid to overload a function with all parameters optional 
with a function that takes no parameters. The parameterless 
overload is called if no arguments are passed:
```D
import std.stdio;
void fun(int x = 0, int y = 0) {
     writeln(i"fun($(x), $(y))");
}
void fun() {
     writeln("fun()");
}

fun(y:42); // fun(0, 42)
fun(); // fun()
```

Same rules apply to class constructors:
```D
import std.stdio;
class C {
     this(int x = 0, int y = 0) {
          writeln(i"C($(x), $(y))");
     }
     this() {
         writeln("C()");
     }
}

auto c1 = new C(y:42); // C(0, 42)
auto c2 = new C(); // C()
```

D disallows parameterless constructors for structs, and there are 
good reasons for this. But constructors with all parameters 
optional are prohibited too. This restriction doesn’t make much 
sense, especially now when D supports named arguments. This 
should be valid:

```D
struct S {
     this(int x = 0, int y = 0) {
          writeln(i"S($(x), $(y))");
     }
}
auto s1 = S(y:42); // S(0, 42)
auto s2 = S(); // default initialization
```


More information about the dip.ideas mailing list