On 10/16/16 9:58 AM, Andrei Alexandrescu wrote:
I was thinking it would be handy if tuples had a way to access a field
by name at runtime. E.g.:

Tuple!(int, "a", double, "b") t;
string x = condition ? "a" : "b";
double v = t.get!string(x, 3.14);

The get method takes the field name and the type of the presumed field,
and it returns the value of the field in the tuple. If no field by that
name and type, return the second argument.

Rquirements:

* Do not throw - allow the second argument to be a throwing delegate

* Do not add overhead if the method is never used

* Figure out a reasonable (but not all too complicated) way to deal with
implicit conversions, e.g. if x == "a" in the the code above, should it
return 3.14 or convert the int to double?

* Handle qualifiers appropriately

Why not something like this:

Val get(T, Val)(auto ref T item, string memberName, Val defaultValue)
{
   switch(memberName)
   {
   foreach(n; __traits(allMembers, T))
   {
      static if(is(typeof(__traits(getMember, item, n)) : Val))
        case n: mixin("return item." ~ n ~ ";");
   }
   default:
     return defaultValue;
   }
}

1. It's opt-in, no code is added to the binary if you don't use it.
2. works for any type, not just Tuple.

Note: no testing, this needs probably some work to get it reasonable, e.g. need to filter out private members. Maybe Jack Stouffer's PR is a better start.

-Steve

Reply via email to