Member Access Based On A Runtime String
Jack Stouffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Mar 1 07:40:56 PST 2016
On Tuesday, 1 March 2016 at 08:53:20 UTC, Adrian Matoga wrote:
> struct Foo
> {
> string foo = "dog";
> int bar = 42;
> int baz = 31337;
> }
>
> void set(P, T)(ref P p, string name, auto ref T value)
> {
> foreach (mem; __traits(allMembers, P)) {
> static if (is(typeof(__traits(getMember, p, mem)) Q)) {
> static if (is(Q : T)) {
> if (mem == name) {
> __traits(getMember, p, mem) = value;
> return;
> }
> }
> }
> }
> assert(0, P.stringof ~ " has no member " ~ name);
> }
>
> unittest
> {
> Foo foo;
> foo.set("bar", 15);
> assert(foo.bar == 15);
> foo.set("foo", "cat");
> assert(foo.foo == "cat");
> }
Thanks. This should be in Phobos
More information about the Digitalmars-d-learn
mailing list