Optional type - how to correctly reset a wrapped immutable T

aliak something at something.com
Sun Mar 25 21:26:57 UTC 2018


Hi, I have this optional type I'm working on and I've run in to a 
little snag when it comes to wrapping an immutable. Basically 
what I want is for an Optional!(immutable T) to still be settable 
to "some" value or "no" value because the Optional wrapper itself 
is mutable.

Optional!(immutable int) a = some(3);
a = none;

I used to do this via a dynamic array and opAssign would recreate 
the array

struct Optional(T) {
   T[] bag;
   opAssign(T t) {
     bag = [t]
   }
}

But then there were problems with inout, namely:

Error: variable `Optional!(inout(A)).Optional.bag` only 
parameters or stack based variables can be inout

So I changed it to a stack variable (prefer this anyway, it's not 
only because of the inout error) but now I'm unsure if I'm 
violating the type system. Basically I'm now storing T as 
Unqual!T, but what I'm looking for is a Rebindable implementation 
that's for value types as well. Is this possible?

Now I do this:

struct Optional(T) {
   Unqual!T value;
   opAssign(T t) {
     value = cast(Unqual!T)(t);
   }
}

I put up a PR if anyone wants to see the code. Any pointers, tips 
would be highly appreciated:

https://github.com/aliak00/optional/pull/13/files#diff-cb543fea6a0b5eeb07b6aac9f068e262

Cheers
- Ali




More information about the Digitalmars-d-learn mailing list