switch to member
Ignacious via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Jan 14 08:06:54 PST 2017
On Saturday, 14 January 2017 at 11:32:10 UTC, Marc Schütz wrote:
> You can utilize a little-known `switch` syntax trick in
> combination with `foreach`. Because a `foreach` over tuples is
> unrolled at compile time, it works even if your fields don't
> have exactly the same types:
>
> --------------------------------------------------------------
>
> struct Foo {
> int x, y;
> long a, b, c;
> short i, j, k;
> }
>
> enum Which {
> x, y, a, b, c, i, j, k,
> }
>
> void assignValue(ref Foo q, Which member, short e) {
> import std.traits : EnumMembers;
> import std.conv : to;
>
> final switch(member) {
> // foreach over a tuple is unrolled at compile time
> foreach(w; EnumMembers!Which) {
> case w:
> // expands to: q.x, q.y, ...
> mixin("q." ~ w.to!string) = e;
> break;
> }
> }
> }
>
> void main() {
> import std.stdio : writeln;
> Foo q;
> writeln("before: ", q);
> assignValue(q, Which.a, 42);
> assignValue(q, Which.x, 1);
> writeln("after: ", q);
> }
Cool, pretty straightforward and somewhat easy to use. I suppose
it might be easier to mark the enum members with an attribute
though and use that rather than having two enums? I didn't know
about the foreach in the switch, cool idea!
Thanks.
More information about the Digitalmars-d-learn
mailing list