get from tuple by type
ketmar via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Mar 15 15:21:04 PDT 2015
On Sun, 15 Mar 2015 21:59:16 +0000, Charles Cooper wrote:
> 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.
why indexing? functional programming is fun!
import std.typecons : tuple;
template GetByType(Type, Tuple...) {
import std.typecons : isTuple;
static if (Tuple.length == 0)
static assert(false, Type.stringof~" not found");
else static if (Tuple.length == 1 && isTuple!(typeof(Tuple[0])))
enum GetByType = GetByType!(Type, Tuple[0].expand);
else static if (is(typeof(Tuple[0]) == Type))
enum GetByType = Tuple[0];
else
enum GetByType = GetByType!(Type, Tuple[1..$]);
}
static assert(2.5 == GetByType!(double, 1, 2.5));
static assert(2.5 == GetByType!(double, 1, 2.5, 3.1));
//static assert(2.5 == GetByType!(char, 1, 2.5, 3.1));
static assert(2.5 == GetByType!(double, std.typecons.tuple(1, 2.5)));
static assert(2.5 == GetByType!(double, std.typecons.tuple(1,2.5,3.1)));
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 181 bytes
Desc: not available
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20150315/feee8478/attachment.sig>
More information about the Digitalmars-d-learn
mailing list