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:
Add a compile-time parameter to your function.
Use
static if
ormixin
to modify the code based on that parameter.Then add
alias
specific sets of parameters to user-friendly names usingalias 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...