Difference between revisions of "Finding all Functions in a Module"
m |
m |
||
Line 17: | Line 17: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | Note that | + | Note that [http://dlang.org/traits.html#allMembers __traits(allMembers, XXX)] returns a tuple of ''strings'', not a tuple of symbols. |
To iterate on this tuple, a simple foreach works very well: | To iterate on this tuple, a simple foreach works very well: | ||
Line 28: | Line 28: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | Inside the ''foreach'' loop, we can use | + | Inside the ''foreach'' loop, we can use [http://dlang.org/traits.html#getMember __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 [http://dlang.org/traits.html#isStaticFunction __traits(isStaticFunction, XXX)]: |
==Program Code== | ==Program Code== |
Revision as of 13:36, 23 March 2014
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:
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