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:

  1. Nested scope
  2. 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 scope
void 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 5
x = 4;
writeln("x = ", x); // prints 4
}

Explanation

  • Line 3: We create our template mixin mixin template Foo() using the mixin and template keywords.
  • Line 4: We declare a variable x and 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 the Foo mixin. Because in the Foo mixin, we have x defined with the value of 5.
  • Line 12: We change the value of x to 4.
  • Line 13: We print the new x value to the screen.

Free Resources