Manually calling postblots recursively
Johannes Loher via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jun 18 02:41:01 PDT 2017
Hey, I'm trying to work on
https://issues.dlang.org/show_bug.cgi?id=15708 so I decided it
might be interesting to find a way to (recursively) call all
postblits that belong to certain struct or static array. This is
what I came up with so far:
import std.traits;
void callPostblits(S)(ref S s)
{
static if (isStaticArray!S && S.length)
{
foreach (ref elem; s)
callPostblits(elem);
}
else static if (is(S == struct))
{
foreach (field; FieldNameTuple!S)
{
callPostblits(__traits(getMember, s, field));
}
static if (hasMember!(S, "__postblit"))
{
s.__postblit();
}
}
}
@safe unittest
{
struct AnotherTestStruct
{
int b = 0;
this(this)
{
b = 1;
}
}
struct TestStruct
{
int a = 0;
this(this)
{
a = 1;
}
AnotherTestStruct anotherTestStruct;
}
TestStruct[2] testStructs;
assert(testStructs[0].a == 0 &&
testStructs[0].anotherTestStruct.b == 0);
assert(testStructs[1].a == 0 &&
testStructs[1].anotherTestStruct.b == 0);
callPostblits(testStructs);
assert(testStructs[0].a == 1 &&
testStructs[0].anotherTestStruct.b == 1);
assert(testStructs[1].a == 1 &&
testStructs[1].anotherTestStruct.b == 1);
}
Any suggestions for improvement or cases where this fails?
More information about the Digitalmars-d-learn
mailing list