Pointer to variables in D

Nathan M. Swan nathanmswan at gmail.com
Wed Apr 25 20:54:24 PDT 2012


On Thursday, 26 April 2012 at 02:43:35 UTC, Victor Vicente de 
Carvalho wrote:
> Hi there,
>
> In c++ one can access a pointer to a class/struct variable 
> using this semantic:
>
> struct C {
>  int x;
> };
>
> int C::* ptr = &C::x;
>
> C foo;
>
> foo.*ptr = 10;
> assert(foo.x == 10);
>
> It is possible to do something like that on D? I've searched 
> through the forum & documentation but didn't found anything.


This is the closest thing:

---
struct C {
  int x;
  int* ptr() @property { return &x; }
}

C foo;
*foo.ptr = 10;
assert(foo.x = 10);
---

> Also, the reason of this is that I'm studying a way to map a 
> POD structure based from a dynamic, data-driven structure. 
> Something like "get a JSON and map it to a structure 
> automagically". There is a nicer way to do that in D?

Yes. My rule: don't use pointers unless doing it otherwise is 
really slow or really hard.


More information about the Digitalmars-d-learn mailing list