Skip to content

Instantly share code, notes, and snippets.

@ylegall
Last active December 18, 2015 04:19
Show Gist options
  • Save ylegall/5724827 to your computer and use it in GitHub Desktop.
Save ylegall/5724827 to your computer and use it in GitHub Desktop.
gist to demonstrate querying methods for annotations (user defined attributes) in D.
import std.traits;
import std.stdio;
// A custom attribute:
struct Test
{
bool enabled = true;
int timeout = 5000;
}
class MyTest
{
@Test
void foo() {
writeln("in foo()");
}
/// TODO: this does not work yet
@Test
void bar(int i) {
writefln("in bar(%d)", i);
}
/// TODO: this does not work yet
@Test(false, 4000)
void baz() {
writefln("in baz()");
}
}
/// determine if the type X is contained in T...
template hasTag(X, T...) {
//pragma(msg, T);
static if (T.length) {
static if (is(T[0] : X)) {
enum hasTag = true;
} else {
enum hasTag = hasTag!(X, T[1 .. $]);
}
} else {
enum hasTag = false;
}
}
auto invokeTestMembers(T)(T type) {
foreach (fn; __traits(allMembers, T)) {
debug writeln("fn = ", fn);
if (hasTag!(Test, __traits(getAttributes, __traits(getMember, type, fn) ))) {
debug writeln("\ttest method!");
static if (__traits(compiles, __traits(getVirtualFunctions, type, fn)[0]())) {
__traits(getVirtualFunctions, type, fn)[0]();
}
}
}
}
void main()
{
auto myTest = new MyTest();
invokeTestMembers(myTest);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment