July 28, 2015 Select value from list, indexed by a type | ||||
|---|---|---|---|---|
| ||||
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 );
It would help with unittest definitions, such as:
foreach (F; TypeTuple!(float, double, real))
{
Tuple!(F, int)[] vals = // x, ilogb(x)
[
tuple( 2.0001 , 1 ),
tuple( 1.9999 , 0 ),
// ...
tuple(-F.min_normal, somethingie!(F, float, double, real)(-126, -1022, -16382),
];
foreach(elem; vals)
{
assert(ilogb(elem[0]) == elem[1]);
}
}
Thanks!
(on IRC, I was advised to move the special case of min_normal outside of the loop. Perhaps more people like that better, but still I am interested in knowing if my "somethingie" exists, or whether you think it is useful too. (what if there are 10 such special cases?))
| ||||
July 28, 2015 Re: Select value from list, indexed by a type | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Johan Engelen | 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 );
}
----
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply