Any way to automatically convert structs on return?

IchorDev zxinsworld at gmail.com
Thu Aug 1 08:46:00 UTC 2024


On Thursday, 1 August 2024 at 07:25:53 UTC, Emma wrote:
> This code works:
>
> ```d
> struct None {}
>
> struct Option(T) {
>     bool hasSome;
>     T value;
>
>     this(None) {}
>
>     this(T v) {
>         hasSome = true;
>         value = v;
>     }
> }
>
> Option!int a = 123;    // automatically constructs an 
> Option!int from a bare int
> Option!int b = None(); // same as above but with None
> ```
> but this doesn't:
> ```d
> Option!int something() {
>   return None(); // Error: cannot implicitly convert expression 
> `None()` of type `None` to `Option!int`
> }
> ```
> This kind of prevents ergonomic code like the above. Instead 
> you have to use a function like `Option!T None(T)() => 
> Option!T()` and then you have to repeat yourself with `return 
> None!int` and etc... it's quite annoying :(
>
> In C++ you may do this fairly easily, but of course there are 
> various pitfalls because it's C++. But at least you can opt out 
> with `explicit` most of the time.
>
> Thanks in advance!

I’m pretty sure this is intentional to prevent ambiguity, but I 
can’t quite remember what the point of that is. You can always 
just write the constructor manually, but yes it’s a hassle. I 
wonder how open people would be to changing this restriction?

P.S. You might want to put `value = void`, otherwise it’ll always 
be default-constructed. Phobos also has `Nullable` if you want 
another implementation for reference.


More information about the Digitalmars-d-learn mailing list