On this page
Templates, Concepts & Polymorphism
Prev: RAII, Smart Pointers & Lifetime | Up: Language & RAII | Next: Compilation, Headers, Modules & ABI
Rel: Templates, Concepts (C++20), Classes, Inheritance & virtual, std::variant
Ref: cppreference — Constraints and Concepts | ISO C++ Core Guidelines
Tags: #public #prog #cpp #templates #polymorphism #tier/standard
Overview
C++ offers three distinct polymorphism mechanisms, letting you choose between zero-overhead static dispatch, open runtime extensibility, and closed value-based sum types.
Comparing the Three Models
| Mechanism | Dispatch | Memory Layout | Extensibility | Best For |
|---|---|---|---|---|
| Templates + C++20 Concepts | Compile-time (monomorphized, inlined) | Stack / inline | Open (duck-typed + constrained) | Generic containers, math, hot inner loops |
virtual Inheritance |
Runtime (vtable pointer) | Usually heap (std::unique_ptr<Base>) |
Open (plugins, new subclasses without recompiling callers) | Heterogeneous collections with open extension points |
std::variant + std::visit |
Runtime (tag switch) | Stack / inline (size of largest member) | Closed set of types | AST nodes, protocol messages, finite state machines |
Constrained Static Polymorphism Example
#include <concepts>
#include <iostream>
template <typename T>
concept Drawable = requires(const T& obj) {
{ obj.draw() } -> std::same_as<void>;
};
void render_all(const Drawable auto& item) {
item.draw(); // inlined directly — zero vtable overhead
}
Choosing Wisely
- Prefer templates + concepts when types are known at compile time and performance matters.
- Prefer
std::variantwhen the set of variants is closed and you want value semantics without heap allocations. - Prefer
virtualinterfaces when you need runtime heterogeneity across an open set of implementations (always withvirtual ~Base() = default;).
Linked from
Related notes
- tuts/cpp/builtins/classes_and_virtual Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/concepts Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/templates Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/language_and_raii/compilation_headers_modules_and_abi Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/language_and_raii/raii_smart_pointers_and_lifetime Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/stdlib/containers/variant Linked here; links to this page; shared tags: #cpp, #prog, #tier
- tuts/cpp/language_and_raii Linked here; links to this page; shared tags: #cpp, #prog
- tuts/cpp/builtins/auto shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/c_style_casts shared tags: #cpp, #prog, #tier
- tuts/cpp/builtins/casts shared tags: #cpp, #prog, #tier