4 ms·
it allows to generate code at basically every scope and to create your own "base language elements" like "struct", "class". AFAIK D does not allow for this, doe
by jcelerier 6y ago
it allows to generate code at basically every scope and to create your own "base language elements" like "struct", "class". AFAIK D does not allow for this, does it ?
- acehreli 6y agoD's templates has always been very strong and useful compared to C++'s. The following example is similar to C macros because it generates code as string and mixes it in as code but you can combine templates as well. This example generates a struct definition. (Edit: formatting) import std; // Entire package for brevity auto memberDef(string type, string name) { return format!" %s %s;"(type, name); } auto memberDefs(string[] members...) { return (members .chunks(2) .map!(pair => memberDef(pair[0], pair[1]))); } auto structDef(string name, string[] members...) { return format!q{ struct %s { %-(%s%) } }(name, memberDefs(members)); } unittest { mixin (structDef("Foo", "int", "i", "double", "d")); auto f = Foo(42, 1.5); assert((f.i == 42) && (f.d == 1.5)); } void main() { }