Labels in struct
Adam D. Ruppe via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jan 31 08:13:27 PST 2015
You could use a UDA like that, though getting the offset will be
a bit tricky.
The idea is to use some uda type, even plain string is good
enough, then use the __traits to find the first appearance of
that UDA in the object and return that offset.
Keep in mind that the @uda: syntax applies it to ALL following
members, it isn't really a label, but if we only look at the
first time it shows up we can kinda pretend it is one.
Here's an example:
struct Foo {
int b;
@("label_one"): // offset 4
int c;
int d;
@("label_two"): // offset 12
int e;
}
// get the offset of the label on a type, see below for usage
size_t offsetOf(T, string label)() {
foreach(memberName; __traits(allMembers, T)) {
foreach(attribute; __traits(getAttributes, __traits(getMember,
T, memberName))) {
static if(is(typeof(attribute) == string) && attribute ==
label)
return __traits(getMember, T, memberName).offsetof;
}
}
assert(0, "no such label");
}
void main() {
// gives what we expect
pragma(msg, offsetOf!(Foo, "label_one"));
pragma(msg, offsetOf!(Foo, "label_two"));
}
More information about the Digitalmars-d-learn
mailing list