On 5/27/15 6:21 PM, Artur Skawina via Digitalmars-d wrote:

But with alias this, we can define a way to solve all these problems.

struct SPtr(T)
{
     ptrdiff_t _offset;
     void opAssign(T *orig) { _offset = cast(void *)orig - cast(void *)&this;}
     inout(T) *_get() inout { return cast(inout(T)*)((cast(inout(void) *)&this) 
+ _offset);}
     alias _get this;
}

Basically, instead of storing the pointer, we store the offset to the struct 
itself. This works as long as the SPtr instance stays co-located with its 
target.

   auto a = s.y;
   // this 'a' now implicitly converts to 'int', but...

   void g(T)(T a);
   g(s.y);         // ditto.


Yes, both your cases (including the one that I didn't quote) show that such constructs must be controlled privately. For example, S should really be written like this:

struct S
{
  int x;
  private SPtr!int _y;
  int *y() {return _y;}
  void y(int * newy) { _y = newy; }
}

And it gets kind of sticky from there if you wanted to replace an actual variable :) For example, y++.

But you can get most of the abilities of a member and still not destroy the semantic of having it reference the copy.

I actually need this in the project I'm writing, which I'm hoping to get into Phobos, and I'm either going to define it in that project, or define it in std.typecons. Maybe the best thing to do is to define it privately for that module, and then move it somewhere more public if it turns out to be something that's useful elsewhere.

-Steve

Reply via email to