In C and C++, a tagged union can be created from untagged unions using a strict
access discipline where the tag is always checked:
enum ShapeKind { Square, Rectangle, Circle };
struct Shape {
int centerx;
int centery;
enum ShapeKind kind;
union {
struct { int side; }; /* Square */
struct { int length, height; }; /* Rectangle */
struct { int radius; }; /* Circle */
};
};
int getSquareSide(struct Shape* s) {
assert(s->kind == Square);
return s->side;
}
void setSquareSide(struct Shape* s, int side) {
s->kind = Square;
s->side = side;
}
/* and so on */