An Optional!T and the implementation of the underlying type's opUnary
aliak
something at something.com
Wed Jul 25 21:59:00 UTC 2018
On Wednesday, 25 July 2018 at 18:01:54 UTC, Atila Neves wrote:
>
> This works for me:
>
> struct Optional(T) {
>
> private T _value;
> private bool empty = true;
>
> this(T value) {
> _value = value;
> empty = false;
> }
>
> auto opUnary(string op)() {
> if(!empty) mixin(op ~ "_value;");
> return this;
> }
>
> string toString() const {
> import std.conv: text;
> return empty
> ? "None!" ~ T.stringof
> : text("Some!", T.stringof, "(", _value.text, ")");
> }
> }
>
>
> void main() {
> import std.stdio;
>
> Optional!int nope;
> writeln(nope);
>
> auto mut = Optional!int(3);
> ++mut; // compiles
> writeln(mut);
>
> immutable imut = Optional!int(7);
> // ++imut; // error
> }
It needs to work with const as well and immutable too.
immutable a = 3;
auto b = -a; // is ok, should be ok with the optional as well.
Plus T can be a custom type as well with "some" definition of
opUnary. I can't seem to find any implementation guidelines
either so I assume opUnary or any of the ops implementation
details is implementation defined.
More information about the Digitalmars-d
mailing list