Merging two named Tuples
Edwin van Leeuwen via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Oct 24 04:04:11 PDT 2015
I am trying to write a function to merge two named structs, but
am completely stuck on how to do that and was wondering if anyone
good provide any help. I know I can access the different names
with tup.fieldNames, but basically can't work out how to use that
to build the new return type. Below is an outline of what I am
trying to do (with unittest). Any pointers would be greatly
appreciated.
/++
Merge two Aes structs
If it has similar named types, then it uses the second one.
Returns a new struct, with combined types.
+/
import std.typecons : Tuple;
template merge(T, U)
{
auto merge( T base, U other )
{
// Go over other.fieldNames and collect them for new tuple
// Go over base.fieldNames, ignoring the ones that other
has as well
// Build newTuple
return newTuple;
}
}
///
unittest
{
auto xs = ["a","b"];
auto ys = ["c","d"];
auto labels = ["e","f"];
auto aes = Tuple!(string[], "x", string[], "y", string[],
"label")(
xs, ys, labels );
auto nlAes = merge( aes, Tuple!(double[], "x",
double[], "y" )(
[0,1], [3,4] ) );
assertEqual( nlAes.x[0], 0 );
assertEqual( nlAes.label.front, "e" );
}
More information about the Digitalmars-d-learn
mailing list