Bypassing const with a union
    Ali Çehreli 
    acehreli at yahoo.com
       
    Fri Jun  1 14:15:16 PDT 2012
    
    
  
On 06/01/2012 01:24 PM, Era Scarecrow wrote:
 > Good, but if I wanted to return an const item (as above) we have an
 > issue. Since I want to change the pointer (but not it's contents) as a
 > slice, the const system gets in the way without duping it.
 >
 > //from const, to const
 > const(S) opSlice(int s, int e) const {
 > S s = this; //compile error this.array is const
 > s.array = this[s .. e]; //compile error
 > return s;
 > }
Don't forget inout, which seems to be working at least in this case:
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();
}
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.
Ali
-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html
    
    
More information about the Digitalmars-d-learn
mailing list