Template Mixins

You will be acquainted with template mixins in this lesson.

Mixins are for mixing generated code into the source code. The mixed-in code may be generated as a template instance or a string.

Code can also be inserted into the program as a string import.

Template mixins

We have seen in the templates and more templates chapters that templates define code as a pattern, for the compiler to generate actual instances from that pattern. Templates can generate functions, structs, unions, classes, interfaces, and any other legal D code.

Template mixins insert instantiations of templates into the code by the mixin keyword:

mixin a_template!(template_parameters)

As you will see in the example below, the mixin keyword is used in the definitions of template mixins as well.

For the specific set of template parameters, the instantiation of the template is inserted into the source code right where the mixin keyword appears.

For example, let’s take a template that defines both an array of edges and a pair of functions that operate on those edges:

Get hands-on with 1400+ tech skills courses.