On this page
  1. Templates, Concepts & Polymorphism
  2. Overview
  3. Comparing the Three Models
  4. Constrained Static Polymorphism Example
  5. Choosing Wisely

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

Linked from

Related notes