Getting the address of a field... when the field might be a property function
struct S { private int n; ref int prop() return { return n; } } auto ref eval(T)(auto ref T t) { return t; } /// How do we get a pointer to n? unittest { auto s = S(13); auto p1 = &s.prop; // wrong auto p2 = &(s.prop); // wrong // auto p3 = &(x => x)(s.prop); // error int* p4 = &eval(s.prop); // eval helper assert(typeof(p1).stringof == "int delegate() ref return"); assert(typeof(p2).stringof == "int delegate() ref return"); assert(p2() == 13); (*p4)++; p4[0]++; assert(p1() == 15); // technically works, but requires this code to be in the same module as // S's definition, and requires us to know the name of the real variable. // what if S is a user-provided type? int* p5 = &s.n; // eval works for fields as well int* p6 = &eval(s.n); }
Discussion (especially this post)