3 ms·
If I remember correctly there was even a special clause in the C standard definition of union types which allows you to write: struct A { Data header; ... } s
by fmap 13y ago
If I remember correctly there was even a special clause in the C standard definition of union types which allows you to write:
struct A { Data header; ... }
struct B { Data header; ... }
union AB { Data header; A a; B b }
and then access the header field in AB. If this is syntactically the first field in each of the constituent records the result is well-defined.
This is a great solution if you need to map to a specific wire format. If you do not have that constraint and have code which uses algebraic data types a lot you should probably switch to OCaml or Haskell. There are specific optimizations to work with complex matches and for representing algebraic types in a compact and efficient way. In C++ the compiler has to work with reinterpret_casts and cannot change the representation of your data types (much). Doing the optimizations by hand is possible, but chances are that a simple-minded OCaml prototype will already perform reasonably well.