C++ mutable in D

Dukc ajieskola at gmail.com
Sun Aug 1 10:50:19 UTC 2021


On Friday, 30 July 2021 at 19:17:55 UTC, Michael Galuza wrote:
> Is there any analogue of C++ `mutable` in D? As far as I 
> understand, this is impossible due to transitive constness, but 
> maybe some variation of `Rebindable` will be useful?
>
> P.S. Of course I mean 'fair' mutable, not qualifier-away 
> `cast()`.

Not any good analogue. There are some situation-dependant 
possibilities though. First one, you could do some template 
magic. Something like:

```d
template constIf(bool cond, T)
{ static if(cond) alias constIf = const(T);
   else alias constIf = T;
}

struct AType(bool isConst)
{ constIf!(isConst, int[]) a;
   constIf!(isConst, int[]) b;
   int[] iPretendToBeMutable;
}
```

Second possibility is that you store the mutable "element" in 
some external data structure, and store it's key or index in the 
`const` `struct`/`class`. This is what I'd probably do.


More information about the Digitalmars-d mailing list