Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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:

  1. Create a switch statement.

  2. If you are looping over a tuple of strings, such as one from a template argument list or returned from __traits, you can write the case statements inside the foreach loop.

  3. Otherwise, build the code as a string and use the mixin expression to add it to your switch statement.

  4. 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:
    ...