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.
Let's execute the following steps to use string parameters to change functions:
static if
or mixin
to modify the code based on that parameter.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(); }
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.
3.147.85.221