Simplify some C-style code
Jim Balter
Jim at Balter.name
Wed Dec 25 21:59:52 UTC 2024
On Wednesday, 25 December 2024 at 18:25:57 UTC, sfp wrote:
>kind of weird that it doesn't work inside `enum`.
> Seems like an obvious application...
It's not weird at all when you understand that it's an AST that
is being mixed in, not just a string as if it were an C
preprocessor macro. The insides of `enum { ... }` is not an
expression so it makes no sense to try to mix in an expression.
enums are
indeed an obvious application for mixins, but that's just not the
way you do it. Here's are some mixins I wrote just yesterday:
```
string membersListMixin(alias T)() {
string s;
foreach (member; __traits(allMembers, T)) {
s ~= member ~ ", ";
}
return s;
}
enum NamedEnum { // named so I can generate its fields
field1 = "string1",
field2 = "string2",
// ...
}
void foo() {
foreach (field; mixin(`[`, membersListMixin!NamedEnum, `]`)) {
// do something with field
}
}
string anonymousEnumMixin(alias E)() {
string s = "enum { ";
foreach (member; __traits(allMembers, E)) {
s ~= member ~ " = " ~ E.stringof ~ "." ~ member ~ ", ";
}
return s ~ "}";
}
mixin(anonymousEnumMixin!NamedEnum);
// now I can refer to field1, field2, etc. without qualifying
them.
```
More information about the Digitalmars-d-learn
mailing list