Skip to content

Instantly share code, notes, and snippets.

@Yoplitein
Last active September 3, 2018 17:20
Show Gist options
  • Save Yoplitein/f8eb9888f3927018cd7610d4a204e8e6 to your computer and use it in GitHub Desktop.
Save Yoplitein/f8eb9888f3927018cd7610d4a204e8e6 to your computer and use it in GitHub Desktop.
D function to easily construct nested structs
import std.traits;
Type construct(Type)(RepresentationTypeTuple!Type args)
{
static union Conv
{
Type obj;
struct { typeof(args) fields; }
}
Conv conv;
conv.fields = args;
return conv.obj;
}
unittest
{
struct Parent
{
int x;
}
struct Child
{
Parent parent;
int y;
}
static assert(__traits(compiles, construct!Child(1, 2)));
Child child = construct!Child(1, 2);
assert(child.parent.x == 1);
assert(child.y == 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment