Select value from list, indexed by a type

anonymous via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 28 14:37:18 PDT 2015


On Tuesday, 28 July 2015 at 21:12:13 UTC, Johan Engelen wrote:
> Hi all,
>   I am wondering if there is any Phobos functionality for 
> indexing into a list using a type. What I mean is something 
> like:
>
> assert(  somethingie!(float,  float, double, real)(1, 22, 333) 
> == 1  );
> assert(  somethingie!(double, float, double, real)(1, 22, 333) 
> == 22  );
> assert(  somethingie!(real,   float, double, real)(1, 22, 333) 
> == 333  );

std.typetuple.staticIndexOf (going to be moved to std.meta in 
2.068) can do this together with std.typecons.tuple:
----
void main()
{
     import std.typetuple: staticIndexOf;
     import std.typecons: tuple;
	
     assert(tuple(1, 22, 333)[staticIndexOf!(float,  float, 
double, real)] == 1);
     assert(tuple(1, 22, 333)[staticIndexOf!(double, float, 
double, real)] == 22);
     assert(tuple(1, 22, 333)[staticIndexOf!(real,   float, 
double, real)] == 333);
}
----

Or if you think that's worth encapsulating in somethingie:
----
template somethingie(T, TList...)
{
     auto somethingie(A...)(A args)
     {
         import std.typetuple: staticIndexOf;
         import std.typecons: tuple;

         return tuple(args)[staticIndexOf!(T, TList)];
     }
}

void main()
{
     assert(  somethingie!(float,  float, double, real)(1, 22, 
333) == 1  );
     assert(  somethingie!(double, float, double, real)(1, 22, 
333) == 22  );
     assert(  somethingie!(real,   float, double, real)(1, 22, 
333) == 333  );
}
----



More information about the Digitalmars-d-learn mailing list