Search code examples
templatesmixinsdtemplate-mixins

Mixin template for defining structs with identical member


I want to define a number of structs, each starting with the same member:

struct A {
    S s; // same member
    X x; // other members
}

struct B {
    S s; // same member
    Y y; // other members
}

What is a mixin template to achieve this?


Solution

  • import std.array;
    
    struct S {}
    struct X {}
    struct Y {}
    
    mixin template Common() {
       S s; // same member
    }
    
    string struct_factory(string name, string[] args...) {
        return `struct ` ~ name ~ ` { 
                    mixin Common;
                ` ~ args.join("\n") ~ `
                }`;
    }
    
    mixin(struct_factory("A", "X x;"));
    mixin(struct_factory("B", "Y y;"));
    
    void main() {
        A a;
        B b;
    }
    

    Or (hide the string-mixin):

    import std.array;
    
    struct S {}
    struct X {}
    struct Y {}
    
    private string struct_factory(string name, string[] args...) {
        return `struct ` ~ name ~ ` { 
                    mixin Common;
                ` ~ args.join("\n") ~ `
                }`;
    }
    
    mixin template Common() {
        S s;
    }
    
    mixin template Struct(string name, Args...) {
        mixin(struct_factory(name, [Args]));
    }
    
    mixin Struct!("A", "X x;");
    mixin Struct!("B", "Y y;");
    
    
    void main() {
        A a;
        B b;
    }