Optional type - how to correctly reset a wrapped immutable T

Simen Kjærås simen.kjaras at gmail.com
Sun Mar 25 23:00:11 UTC 2018


On Sunday, 25 March 2018 at 21:26:57 UTC, aliak wrote:
> struct Optional(T) {
>   Unqual!T value;
>   opAssign(T t) {
>     value = cast(Unqual!T)(t);
>   }
> }

Consider this case:

Optional!(immutable int) a = some(3);
immutable int* p = &a.value;
a = some(5);

Clearly the above code shouldn't compile - you can't overwrite 
the value, as it would break immutability. If you want to support 
both immutability and reassignment, you will need to use 
redirection - either an array as you did, or a pointer.

As for the problems you've had with inout, I wrote this template 
a few years back:

template SubstituteInout(FromType, ToType) {
     static if (is(ToType == inout(SubType), SubType)) {
         alias SubstituteInout = CopyTypeQualifiers!(FromType, 
SubType);
     } else static if (is(ToType == SubType*, SubType)) {
         alias SubstituteInout = SubstituteInout!(FromType, 
SubType)*;
     } else static if (is(ToType == SubType[], SubType)) {
         alias SubstituteInout = SubstituteInout!(FromType, 
SubType)[];
     } else static if (is(ToType == SubType[n], SubType, size_t 
n)) {
         alias SubstituteInout = SubstituteInout!(FromType, 
SubType)[n];
     } else static if (is(ToType == SubType[KeyType], SubType, 
KeyType)) {
         alias SubstituteInout = SubstituteInout!(FromType, 
SubType)[SubstituteInout!(FromType, KeyType)];
     } else {
         alias SubstituteInout = ToType;
     }
}

unittest {
     static assert(is(SubstituteInout!(const(string), int) == 
int));
     static assert(is(SubstituteInout!(const(string), 
inout(int)[]) == const(int)[]));
     static assert(is(SubstituteInout!(const(string), inout(int)) 
== const(int)));
     static assert(is(SubstituteInout!(const(string), 
inout(int)*[][3][int]) == const(int)*[][3][int]));
     static assert(is(SubstituteInout!(const(string), 
inout(int)[inout(string)]) == const(int)[const(string)]));
}

I really should get around to making a PR for it...

--
   Simen


More information about the Digitalmars-d-learn mailing list