Mixins

28.1 String Mixins

mixin("int x = 5;");                       // compile-time string → code
enum op = "+";
int r = mixin("3 " ~ op ~ " 4");           // 7

string makeStruct(string name, string[] fields)
{
    string code = "struct " ~ name ~ " {";
    foreach (f; fields) code ~= "int " ~ f ~ ";";
    return code ~ "}";
}
mixin(makeStruct("Point3", ["x", "y", "z"]));
Point3 p;
p.z = 3;

// Token strings for readability
mixin(q{
    void hello() { writeln("generated"); }
});

// Mixin types (2.088+)
alias T = mixin("int[]");

28.2 Template Mixins

Template mixins insert declarations into the current scope (like copy-paste, but hygienic and named).

mixin template Counter()
{
    private int count;
    void increment() { count++; }
    int value() const { return count; }
}

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

struct Widget
{
    mixin Counter;                        // insert members
    mixin Properties!(string, "title");
}

Widget w;
w.increment();
w.title = "Hello";
writeln(w.value, w.title);