get from tuple by type

Charles Cooper via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Mar 15 14:59:16 PDT 2015


C++14 has:
template<class T, class... Types> constexpr T& 
get(tuple<Types...>& t);
Which allows you to get a member of the tuple struct by type. Is 
there an idiomatic / library way to do this in D? Preferably by 
indexing.

Here is what I have, it is ugly but works:
/* CODE */
static import std.stdio;
static import std.typecons;
template GetByType(alias tuple_instance, member_t)
{
     ref member_t GetByType() nothrow @nogc @safe {
         alias tuple_t = typeof(tuple_instance);
         static assert(std.typecons.isTuple!tuple_t);
         enum long idx = std.typetuple.staticIndexOf!(member_t, 
tuple_instance.Types);
         static if(-1 != idx)
             return tuple_instance[idx];
         else static assert(false); //better error message
     }
}

static assert(2.5 == GetByType!(std.typecons.tuple(1,2.5), 
double));
static assert(2.5 == GetByType!(std.typecons.tuple(1,2.5,3.1), 
double));
void main() {
     auto foo = std.typecons.tuple(1,2.5);
     std.stdio.writeln(GetByType!(foo, double));
}
/* CODE */

Is there a better way to do this?


More information about the Digitalmars-d-learn mailing list