Skip to content

Instantly share code, notes, and snippets.

@rbscott
Created November 17, 2019 07:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rbscott/ee0f3ba94296f9c8224a8c4c13c2f026 to your computer and use it in GitHub Desktop.
Save rbscott/ee0f3ba94296f9c8224a8c4c13c2f026 to your computer and use it in GitHub Desktop.
immutable struct Field {
string type;
string name;
}
immutable struct Structure {
string name;
Field[] fields;
}
mixin template Named(string name, alias value) {
mixin("alias " ~ name ~ "= value;");
}
template StructureToStruct(Structure structure, alias StructureContainer) {
static struct StructureToStruct {
static foreach(field; structure.fields) {
static if (field.type == "string") {
mixin("string " ~ field.name ~ ";");
} else {
mixin("StructureContainer." ~ field.type ~ " *" ~ field.name ~ ";");
}
}
}
}
const nestedStructureDefintions = [
Structure("Struct1", [Field("string", "a"), Field("Struct2", "struct2")]),
Structure("Struct2", [Field("string", "a"), Field("Struct1", "struct1")]),
];
const flatStructureDefintions = [
Structure("Struct1", [Field("string", "a")]),
Structure("Struct2", [Field("string", "a"), Field("Struct1", "struct1")]),
];
struct Structures {
// Change to nestedStructureDefintions and this will fail.
static foreach (structure; flatStructureDefintions) {
// Is there a better way to rename a struct from a template?
mixin Named!(structure.name, StructureToStruct!(structure, Structures));
}
}
// This on the other hand compiles just fine.
struct NestedStructures {
static struct Struct1 {
string a;
NestedStructures.Struct2 *struct2;
}
static struct Struct2 {
string a;
NestedStructures.Struct1 *struct1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment