Last active
September 3, 2018 17:20
-
-
Save Yoplitein/f8eb9888f3927018cd7610d4a204e8e6 to your computer and use it in GitHub Desktop.
D function to easily construct nested structs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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