Reset all Members of a Aggregate Instance
Tofu Ninja via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Dec 3 20:08:33 PST 2015
On Thursday, 3 December 2015 at 21:04:00 UTC, Nordlöw wrote:
> ...
I think reflection will be a bad choice for this because of
private members and what not.
I think the correct way is:
void reset(C)(ref C c)
{
static if(is(C == class))
{
auto init = typeid(c).init();
auto objmem = ((cast(void*)c)[0 .. init.length]);
if(init.ptr == null) (cast(byte[])objmem)[] = 0;
else objmem[] = init[];
if(c.classinfo.defaultConstructor != null)
c.classinfo.defaultConstructor(c);
}
else c = C.init;
}
Seems to work for structs, classes, and basic types. It even
calls the default constructor for classes, even if there is
inheritance and the object passed in is not actually C but a sub
class of C.
More information about the Digitalmars-d-learn
mailing list