What are template mixins in D?
Overview
Template Mixins are patterns used to generate actual code instances using the compiler in D programming. Codes like functions, structs, unions, classes, interfaces, and any other legal D code can be generated using template mixins.
Syntax
mixin a_template!(template_parameters)
Parameters
Template mixins can be parameterized, this means that they can accept arguments.
import std.stdio : writeln;
mixin template Test(Z)
{
Z x = 5;
}
mixin Test!(int); // create x of type int
Mixin scope
Template mixins have two scopes:
- Nested scope
- Surrounding scope
Mixins are evaluated where their scope is called, not created, and their surrounding scope overrides the global scope.
Example 1
Let’s look at the code below:
import std.stdio : writeln;int a = 7;mixin template Foo(){int a = 50;int b = 50;}mixin Foo;int b = 39; // surrounding scopevoid main(){writeln("b = ", b);}
Explanation
Line 12: The int b value overrides the int b value in line 8.
Example 2
To get a better understanding of template mixins, let’s see the example below:
import std.stdio : writeln;mixin template Foo(){int x = 5;}void main(){mixin Foo;writeln("x = ", x); // prints 5x = 4;writeln("x = ", x); // prints 4}
Explanation
- Line 3: We create our template mixin
mixin template Foo()using themixinandtemplatekeywords. - Line 4: We declare a variable
xand assign a value of 5 to it. - Line 10: We call the created
mixin. - Line 11: We do not define the value of
x, but we can print a value from it after calling theFoomixin. Because in theFoomixin, we havexdefined with the value of 5. - Line 12: We change the value of
xto 4. - Line 13: We print the new
xvalue to the screen.