Traits and UDAs
Chris Williams
yoreanon-chrisw at yahoo.co.jp
Thu Jun 6 10:50:07 PDT 2013
I decided to write up a little application to test using User
Defined Attributes and have one question. Here is a working
application that allows me to mark certain members of a function
to be dumped:
import std.stdio;
enum Dump = "Dump";
template Dumper(T) {
void dump() {
foreach (mem; __traits(allMembers, T)) {
auto attributes = __traits(getAttributes, __traits(getMember,
T, mem));
static if ( attributes.length > 0 && __traits(getAttributes,
__traits(getMember, T, mem))[0] == Dump ) {
writeln(mem);
}
}
}
}
class Foo {
@Dump int hello;
@Dump int world;
int bye;
mixin Dumper!(Foo);
}
int main(string[] args) {
Foo f = new Foo();
f.dump();
return 0;
}
The eighth line bothers me, though. It seems like I should be
able to write:
if (attributes.length > 0 && attributes[0] == Dump)
However, that fails to compile with the message:
test.d(7): Error: variable _attributes_field_0 cannot be read at
compile time
test.d(8): Error: expression !!(_attributes_field_0 == "Dump") is
not constant or does not evaluate to a bool
test.d(7): Error: variable _attributes_field_0 cannot be read at
compile time
test.d(8): Error: expression !!(_attributes_field_0 == "Dump") is
not constant or does not evaluate to a bool
Any thoughts?
More information about the Digitalmars-d-learn
mailing list