Building a lookup table
In the final recipe of the previous chapter on reflection, we built a command-line function caller that did a linear search through all the available functions to find the right one for the command. Here, we'll revisit that concept and generate more efficient code.
How to do it…
Let's execute the following steps to build a lookup table:
Create a
switch
statement.If you are looping over a tuple of strings, such as one from a template argument list or returned from
__traits
, you can write thecase
statements inside theforeach
loop.Otherwise, build the code as a string and use the
mixin
expression to add it to yourswitch
statement.Let the compiler optimize the
switch
statement.
All the preceding steps are mentioned in the following code:
void callFunction(string functionName) { s: switch(functionName) { default: assert(0); // can add defaults or cases outside the loop foreach(methodName; __traits(allMembers, mixin(__MODULE__))) { case methodName: ...