Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 36 ยท Mixins and Metaprogramming

Mixin Templates in D

Learn D mixin templates: injecting fields and methods into classes and structs, parameterized mixins, name lookup rules and when they beat inheritance, with C macro stand-ins.

D has single inheritance, so how do you share an implementation, such as logging or an id counter, between unrelated classes? Mixin templates are the answer. A mixin template is a bundle of declarations (fields, methods, nested types) that you paste into any struct, class or function with mixin Name;. It is code reuse without a common base class.

D code is read-only here. The C stand-ins use macros that inject fields and generate functions, which is as close as plain C gets.

Declaring and using one

D
mixin template Countable()
{
    private static int created;
    int id;

    void assignId() { id = ++created; }
    static int totalCreated() { return created; }
}

class User
{
    mixin Countable;
    string name;
    this(string name) { this.name = name; assignId(); }
}

class Order
{
    mixin Countable;
    double total;
    this(double t) { total = t; assignId(); }
}

Both classes now have id, assignId and their own static counter, even though they share no base. Each class gets an independent copy of created, because the template is instantiated separately in each.

Mixin template or inheritance?

Need Use
"is a" relationship, polymorphic use through a base reference inheritance or interface
Reuse code and data in many unrelated types mixin template
Reuse behavior without data interface with final methods, or a plain template function

A mixin does not create a type relationship: a User is not a Countable. If you also need that relationship, declare an interface and mix in the implementation.

Parameterized mixins

Mixin templates take template parameters like any template:

D
mixin template Property(T, string name)
{
    mixin("private T _" ~ name ~ ";");
    mixin("T " ~ name ~ "() const { return _" ~ name ~ "; }");
    mixin("void " ~ name ~ "(T v) { _" ~ name ~ " = v; }");
}

struct Config
{
    mixin Property!(int, "port");
    mixin Property!(string, "host");
}

This pairs a mixin template with string mixins: one line per property generates a private field with a getter and setter. A C macro can do the same for structs and functions.

C Stand-in: a macro injects a field and its accessors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Injecting into scopes

A mixin template can also be instantiated in a function body to add local declarations, or at module level to add functions. This is handy for repeated boilerplate such as test helpers or a family of similar constants.

D
mixin template Logging()
{
    void log(string msg) { writeln("[", typeof(this).stringof, "] ", msg); }
}

typeof(this).stringof resolves in the place where the mixin lands, so every class prints its own name.

Name lookup rules

Declarations from a mixin template live in a scope of their own, and the compiler resolves conflicts like this:

  1. A name declared directly in the enclosing type wins over a mixed-in name. You can therefore override a default that the mixin supplies.
  2. Two different mixins that supply the same name conflict only if you use the ambiguous name; qualify it with a label to disambiguate: mixin Countable c1; then c1.assignId().
  3. Symbols used inside the mixin are looked up where the template was declared, not where it was mixed in. Unlike string mixins, a mixin template is not text pasting, which makes it much safer.

Stand-in: a default plus an override

The macro below provides a default describe function slot in a struct; a type can overwrite the pointer, like a method that replaces the mixin's default.

C Stand-in: default behavior that a type can override

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Practical uses in D code

  • Boilerplate: equality, hashing and toString for a family of structs.
  • Plugins and registries: a mixin registers the class in a global table when it is declared.
  • Testing: inject the same helper methods into many fixture classes.
  • Platform code: pick a mixin per platform with version.

Keep each mixin template small and focused, name it for the capability (Countable, Observable), and document what it expects from the host type, for instance by adding a static assert(is(typeof(this.name))) at the top.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What problem do mixin templates solve?

    They paste reusable members into any struct or class without a common base.
  2. 2. Does mixing in Countable make User a subtype of Countable?

    A mixin injects members only. Use an interface if you need a type relationship.
  3. 3. If the enclosing class and the mixin both declare describe, which is used?

    Names declared directly in the host type win over mixed-in names.
  4. 4. Where are symbols inside a mixin template looked up?

    This is the key difference from string mixins: it is hygienic, not text pasting.

Summary

  • mixin template bundles members for reuse; mixin Name!(args); injects them.
  • Each use creates independent copies (including static data).
  • The host type's own names override mixed-in ones; the template's symbols are resolved at its declaration.
  • Choose mixins for unrelated types, inheritance for "is a".

Next: Compile-Time Function Execution