On Friday, 2 March 2018 at 19:47:23 UTC, SimonN wrote:
I can envision using this Optional type whenever I want
nullable class reference, and use normal D class references as
non-nullable references together with a codebase-wide rule that
assigning null to normal D references is always a bug.
Ay, maybe you can even have a type that enforces non nullable
references?
(not tested):
struct NonNull(T) if (isPointer!T || is(T == class))
{
T value;
alias value this;
this(Args...)(Args args) { this.value = new T(args); } //
always force creation
}
Hah, I've toyed with some examples, and this stuck out as
verbose because everything else was really smooth. Optional!int
dispatches wonderfully without extra syntax, whereas class C
{}; Optional!C needs the extra dispatch before calling methods.
Yeah, it's unfortunate. If D had custom operators then it
could've been a?.f or whatever :(
So I had to either have a custom function that starts a dispatch
chain or implement opDispatch directly inside Optional. The
problem with the latter is that means if type T has any of the
functions that are part of Optional's interface, they are
basically un-callable unless unwrapped first. I found this
unacceptable.
I'm going to experiment with moving Optional's methods out as
free functions when I get the chance. Then the dynamics between
UFCS/dispatch become a bit weird. And I'm not sure how to work
range functionality in as free functions, but let's see.
If you know of other ways though I'm all ears :)
Cheers