Difference between revisions of "Finding all Functions in a Module"

From D Wiki
Jump to: navigation, search
m
m
Line 17: Line 17:
 
</syntaxhighlight>
 
</syntaxhighlight>
  
Note that ''__traits(allMembers, XXX)'' returns a tuple of ''strings'', not a tuple of symbols.
+
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 ''__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)'':
+
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

Level: Novice
Cookbook Type: Recipe
Cookbook Status: Draft
Approximate reading time: 15 min
0.249 hr
D Version: D2


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