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();
}

How it works…

This is a very straightforward application of the static if block. Since a different function is generated for each set of compile-time parameters, we can change the code with compile-time functions and get pointers or call each individual one with certain bound compile-time parameters, which is similar to a partial application in functional programming languages.

Be careful not to write difficult-to-understand code with this technique. It may often be better to split the function into smaller, more reusable pieces.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.80.45