A Variant which exposes members that are common across all SubTypes.
Two disparate structs ... they can't be used interchangeably, right?
import std.math, std.algorithm; struct Square { float size; float area() { return size * size; } } struct Circle { float r; float area() { return r * r * PI; } } // Or can they? alias Shape = SuperStruct!(Square, Circle); // look! polymorphism! Shape sqr = Square(2); Shape cir = Circle(4); Shape[] shapes = [ sqr, cir ]; // call functions that are shared between the source types! assert(shapes.map!(x => x.area).sum.approxEqual(2 * 2 + 4 * 4 * PI));
Want to access fields of the underlying types? Not a problem! Are some of them properties? Not a problem!
struct Square { int top, left, width, height; } struct Circle { int radius; int x, y; auto top() { return y - radius; } auto top(int val) { return y = val + radius; } } alias Shape = SuperStruct!(Square, Circle); // if a Shape is a Circle, `top` forwards to Circle's top property Shape cir = Circle(4, 0, 0); assert(cir.top = 6); assert(cir.top == 6); // if a Shape is a Square, `top` forwards to Squares's top field Shape sqr = Square(0, 0, 4, 4); assert(sqr.top = 6); assert(sqr.top == 6); // Square.left is hidden, as Circle has no such member static assert(!is(typeof(sqr.left)));
MIT
© 2015, Ryan Roden-Corrent
This module provides a single type, SuperStruct.