Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 451
Core Xii Avatar asked Feb 16 '23 03:02

Core Xii


2 Answers

mixin template Common() {
   S s; // same member
}

struct A {
   mixin Common;
   X x;
}

struct B {
   mixin Common;
   Y y;
}

See Template Mixin

like image 162
Quonux Avatar answered Feb 23 '23 17:02

Quonux


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;
}
like image 35
dav1d Avatar answered Feb 23 '23 18:02

dav1d