Finding all Functions in a Module
Revision as of 20:03, 23 March 2014 by PhilippeSigaud (talk | contribs)
This recipe shows how to list all functions in a module. More generally, it can be used to list all symbols in a module and filter them according to a specific predicate.
First, we need a tuple of all symbol names in a module:
__traits(allMembers, mymodule)
Note that __traits(allMembers, XXX) returns a tuple of strings, not a tuple of symbols.
To iterate on this tuple, a simple foreach works very well. On a tuple, foreach is unrolled at compile-time.
foreach(m; __traits(allMembers, mymodule))
{
//
}
Inside the foreach loop, we can use __traits(getMember, parentSymbol, name) to transform name (a string) into a real symbol. Then static if will test each symbol in turn. Here the predicate is __traits(isStaticFunction, XXX):
Program Code
module mymodule;
import std.stdio : writeln;
void main() {
foreach(m; __traits(allMembers, mymodule))
{
static if (__traits(isStaticFunction, __traits(getMember, mymodule, m)))
writeln(m);
}
}
void myfunc() {}
int myOtherFunc(int i) { return i+1; }
Compilation Output
main myfunc myOtherFunc