Parameter pack expansion
Tomas
skrivantomas at seznam.cz
Thu May 30 20:20:47 UTC 2019
I'm very new to D, coming from C++ I'm missing parameter pack
expansion and fold expressions.
For example, I want to write a function `f(x[0], ..., x[n])`
which accepts any number of objects and calls `g(x[0].member,
..., x[n].member)`.
In C++, I would write this:
template<class ...X>
void f(X ... x){
g(x.member...);
}
Similar transformation can be also done in C++ on types too:
template<class ...X>
using F = G<X::Member...>;
How do I do something like this in D?
Basicaly, how do I preform tuple transformations
X = (X[0], ..., X[n]) -> TX = (X[0].Member, ... ,X[n].Member)
x = (x[0], ..., x[n]) -> tx = (x[0].member, ... ,x[0].member)
Here is my best shot in D, it kind of does what I want, but I
have do define my own map function `myMap`.
// Helper function
auto myMap(alias Fun, X...)(X x) {
import std.typecons;
static if (X.length > 1)
return tuple(Fun(x[0])) ~ myMap!(Fun)(x[1 .. $]);
else
return tuple(Fun(x[0]));
}
// Do the transformation inside
void foo(X...)(X x){
// type transformation
alias MemberOf(T) = T.Member;
alias XM = staticMap!(MemberOf, X);
// value transformation, notice the `expand`!
auto tx = myMap!(x => x.member)(x).expand;
}
What is the recommended what to do this in D? Surely, there has
to be a standard function which does exactly(probably better) the
same thing as what `myMap` does.
More information about the Digitalmars-d-learn
mailing list