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

Using string parameters to change functions


Suppose you have two functions that are identical in most respects but differ in some minor aspects. You need them to be separate functions, but would like to minimize code duplication. There's no obvious type parameterization, but you can represent the difference with a value.

How to do it…

Let's execute the following steps to use string parameters to change functions:

  1. Add a compile-time parameter to your function.

  2. Use static if or mixin to modify the code based on that parameter.

  3. Then add alias specific sets of parameters to user-friendly names using alias friendlyVariation = foo!"argument";.

The code is as follows:

void foo(string variation)() {
        import std.stdio;
        static if(variation == "test")
                writeln("test variation called");
        else
                writeln("other variation called");
}

alias testVariation = foo!"test";
alias otherVariation = foo!"";

void main() {
        testVariation();
        otherVariation...