I'm trying to define a value type which either holds a size_t
or a null
(which is what I mean by a 'maybe type'). What I want to be able to do is something like this (where the relevant type is Maybe!size_t
:
Maybe!size_t something_which_could_fail (int foo) {
if (foo < 0) { return null;}
else { return foo;}
}
How would I implement such a thing? Ideally, I would like to be able to make it a template (so I could have other Maybe
types as well), and have conversions from maybe to non-maybe types be possible as above (although I don't mind typecasting if this is not possible). It would also be nice if I could do something like this:
Maybe!size_t a = 50;
Maybe!size_t b = null;
What about Nullable type in phobos library? http://dlang.org/phobos/std_typecons.html#.Nullable
And some other info in D forum: D forum thread about Option(Maybe) type