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?
mixin template Common() {
S s; // same member
}
struct A {
mixin Common;
X x;
}
struct B {
mixin Common;
Y y;
}
See Template Mixin
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With