Bypassing const with a union
Era Scarecrow
rtcvb32 at yahoo.com
Fri Jun 1 15:51:54 PDT 2012
On Friday, 1 June 2012 at 21:15:18 UTC, Ali Çehreli wrote:
> Don't forget inout, which seems to be working at least in this
> case:
I'd given up on trying to use inout, being as it's confusing to
try and use, when I try to use it it, it always complains.
Perhaps better documentation/examples or I gotta look at it all
over again. To my understanding you had to have inout in the
signature and as a input parameter (which no input arguments
never fit). Hmm..
> import std.traits;
> import std.stdio;
>
> struct S {
> size_t[] array;
>
> void length(size_t length) @property
> {
> array.length = length;
> }
>
> inout(S) copy() inout {
> return this;
> }
>
> inout(S) opSlice(int s, int e) inout {
> Unqual!S sl;
> sl.array = (cast(Unqual!S)this).array[s .. e];
> return cast(inout(S))sl;
> }
> }
>
>
> void main()
> {
> auto s = S();
> s.length = 10;
>
> const s3 = s[0..8];
> const s4 = s3[1..3];
>
> auto sc = s.copy();
> auto s3c = s3.copy();
> }
I'll try and use that, although Unqual is new to me. When going
through the library some of it makes sense and a larger portion
doesn't.
> std.traits.Unqual seems like a dirty trick there but I see it
> being used in Phobos as well.
>
> > struct S {
> > union {
> > size_t[] array;
> > size_t[array.sizeof / size_t.sizeof] nonConst; //since it's a
> fixed array
> > }
>
> I don't understand the calculation there. array.sizeof and
> size_t.sizeof are not related in that way. It works only if
> 'array' is fixed-length as well.
The calculation is rather simple, but not so obvious. Convert to
the size in bytes, then convert that size to how many words
needed for the fixed array to fit. Had array been something a bit
bigger, it would still work (assuming it's evenly divisible).
Course you could always just include a magic number :P.
More information about the Digitalmars-d-learn
mailing list