Any way to automatically convert structs on return?

Emma VuLXn6DBW at PPtUm7TvV6nsw.com
Thu Aug 1 07:25:53 UTC 2024


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!


More information about the Digitalmars-d-learn mailing list