Skip to main content


Showing posts from February, 2018

Inheritance vs std::variant

C++17 added std::variant and std::visit in its repertoire. They are worth a close examination. I've been wondering about whether they are always  better than inheritance for modeling sum-types (fancy name for discriminated unions) and if not, under what circumstances they are not. We'll compare the two approaches in this blog post. So here it goes. Inheritance std::variant Need not know all the derived types upfront (open-world assumption) Must know all the cases upfront (closed-world assumption) Dynamic Allocation (usually) No dynamic allocation Intrusive (must inherit from the base class) Non-intrusive (third-party classes can participate) Reference semantics (think how you copy a vector of pointers to base class?) Value semantics (copying is trivial) Algorithm scattered into classes Algorithm in one place Language supported (Clear errors if pure-virtual is not implemented) Library supported (poor error messages) Creates a first-class abstraction It’s just a conta