Polymorphism Decision Table
Polymorphism Decision Table
A lot of programming languages (e.g. Java and C#) let a programmer achieve polymorphism via a base class with pure virtual functions and derived classes that override these functions. C++ also provides this kind of polymorphism. But C++ comes with additional ways to achieve polymorphism (variant, type erasure and polymorphic_value). In this blog post I will not explain how these features work. There already exists a lot of material about them. I rather want to focus on when to use which kind of polymorphism. For that purpose I created a decision-table that tells you based on which criterions you can use which kind of polymorphism.
Set of Types | Set of Functions | Semantics | Base-Class | Solution |
---|---|---|---|---|
Closed | Closed | Value | No | variant |
Closed | Closed | Value | Yes | PV, variant |
Closed | Closed | Reference | No | TER, variant<SP> |
Closed | Closed | Reference | Yes | SP |
Closed | Open | Value | No | variant |
Closed | Open | Value | Yes | PV+HVP, variant |
Closed | Open | Reference | No | variant<SP> |
Closed | Open | Reference | Yes | SP+HVP, variant<SP> |
Open | Closed | Value | No | TEV |
Open | Closed | Value | Yes | PV |
Open | Closed | Reference | No | TER |
Open | Closed | Reference | Yes | SP |
PV = polymorphic_value
TER = type erasure with reference semantics
TEV = type erasure with value semantics
SP = smart pointer
HVP = hand-written visitor pattern
This decision-table is by no means complete. There exist further criterions that this table does not take into account. Yet it is a helpful guide when one feels overwhelmed by the flexibility of C++.
Further Sources
General
Variant
- Modern C++ Features - std::variant and std::visit
- Everything You Need to Know About std::variant from C++17
Type Erasure
- Better Code: Runtime Polymorphism - Sean Parent
- C++Now 2018: Louis Dionne “Runtime Polymorphism: Back to the Basics”
- CppCon 2019: Arthur O’Dwyer “Back to Basics: Type Erasure”