Named constructors

Quirin Schroll qs.il.paperinik at gmail.com
Thu Jan 16 01:16:33 UTC 2025


On Tuesday, 12 November 2024 at 21:13:18 UTC, IchorDev wrote:
> This is very common practice:
> ```d
> Angle angle(float deg) => new Angle(deg*PI/180f);
> Angle angle(float rad) => new Angle(rad);
>
> auto a = angle(deg: 90);
> auto b = angle(rad: PI/2);
> ```

Function definitions like that don’t work. Parameter names are 
not part of the signature, even if they can participate in 
overload resolution.

You need something like this:
```d
enum Deg { init }
enum Rad { init }
Angle angle(Deg = Deg.init, float deg) => new Angle(deg*PI/180f);
Angle angle(Rad = Rad.init, float rad) => new Angle(rad);
```
Then, the signatures differ by the type(!) of the first 
parameter. Providing a parameter name in a call disambiguates 
overload resolution, and in fact makes using `deg:` or `rad:` a 
requirement.


More information about the dip.ideas mailing list