Artifact
e6efabfb2249290d1e00ddb141a5a121622f24646b48d2995a4ab8636f62fc36:
Wiki page
[get the address of a field] by
admin
2021-10-07 06:44:23.
D 2021-10-07T06:44:23.183
L get\sthe\saddress\sof\sa\sfield
U admin
W 1072
<h3>Getting the address of a field... when the field might be a property function</h3>
<div class="language-d"><verbatim>
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);
}
</verbatim></div>
[https://forum.dlang.org/post/sjkh5i$2p17$1@digitalmars.com|Discussion]
Z 8ef36b36eb939a4eedc1c67912356534