in a template argument, specify which object member to access?

Mengu via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Feb 8 16:13:59 PST 2016


On Monday, 8 February 2016 at 22:46:06 UTC, cy wrote:
> On Monday, 8 February 2016 at 22:38:45 UTC, Mengu wrote:
>> i believe you can use __traits(getMember) there.
>
> Great! Should have refreshed before sending that reply...
>
> I wonder if mixin("a."~member) is better or worse than 
> __traits(getMember,a,member)...

i think it's a matter of taste and here's how i would do it:

import std.stdio;
import std.array;

struct A {
   string up;
   string down;
   string left;
   string right;
}

string goPlaces(args...)(A a) {
   string[] result;
   foreach (arg; args) {
     result ~= __traits(getMember, a, arg);
   }
   return "go " ~ result.join(" then go ");
}

void main() {
   A a = {"north", "south", "east", "west"};
   writeln(goPlaces!("up", "down", "left")(a));
   writeln(goPlaces!("down", "right", "left", "up")(a));
}

// outputs
// go north then go south then go east
// go south then go west then go east then go north


More information about the Digitalmars-d-learn mailing list