Skip to main content

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.

Inheritancestd::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 classesAlgorithm in one place
Language supported (Clear errors if pure-virtual is not implemented)Library supported (poor error messages)
Creates a first-class abstractionIt’s just a container
Keeps fluent interfacesDisables fluent interfaces. Repeated std::visit
Supports recursive types (Composite)Must use recursive_wrapper and dynamic allocation. Not in the C++17 standard.
Adding a new operation (generally) boils down to implementing a polymorphic method in all the classesAdding a new operation simply requires writing a new free function
Use the Visitor design pattern to get some of the benefits of the right hand side

std::variant and std::visit idiom resembles closely to pattern matching in functional languages. However, functional languages are leaps and bounds ahead of the current capabilities of the pattern matching idiom.
  1. Generally, pattern matching makes it easy to dissect a variant type (or even a structured type) by the "shape" of the type and its content. I.e., a more powerful pattern matching in C++ would use structured bindings in some way. 
  2. Conditional structured bindings would match only if the condition is satisfied. 
  3. Matching on the dynamic type of the variable would be really nice but without paying excessive performance cost.
For all these reasons, I think this is best done as a language feature as opposed to a library supported capability. At the moment, it's great to have some basic pattern matching capabilities in C++ that allows you to use both of the styles depending on the problem you're trying to solve.

See a detailed example on slideshare.


Comments

Vittorio Romeo said…
Nice comparison. I created a "pattern-matching like" library to simplify variant/optional declaration/visitation: https://github.com/SuperV1234/scelta

You might find it useful if you work with variants/optionals a lot.
Hassan Raza said…
Nice Information very useful for us..