C++ Idioms & Patterns
63 idioms and design patterns — from classic GoF patterns to C++-specific techniques like CRTP, type erasure, and policy-based design.
Creational Patterns
Create families of related objects without specifying concrete classes — virtual dispatch, std::function, and template policy implementations in C++.
IntermediateConstruct complex C++ objects step-by-step with fluent interfaces. Use type-state builders to enforce mandatory fields at compile time.
IntermediateFactory functions, registry factories, abstract factories, and static create() in modern C++ — ownership, registration, and compile-time vs runtime dispatch.
IntermediatePre-allocate a fixed set of objects and reclaim them without heap allocation — ideal for frequently created objects with bounded lifetimes.
IntermediateC++ prototype pattern — virtual clone with unique_ptr, CRTP clone mixin, deep vs shallow copy, and prototype registry.
BasicThread-safe Singleton in C++ — Meyers singleton, SIOF, static local variable, phoenix singleton, monostate, registry, shared-library pitfalls, and when dependency injection wins.
IntermediateVirtual constructor idiom in C++ — polymorphic object copying via clone(), covariant returns, CRTP mixin, and prototype factory patterns.
IntermediateStructural Patterns
Treat individual objects and groups uniformly through a shared interface — recursive tree operations over leaves and composites without node-type inspection at the call site.
Intermediate"C++ decorator pattern: virtual wrapping, CRTP static decorators, and std::function chaining — ownership, composition, and pitfalls."
IntermediateC++ flyweight pattern — shared intrinsic state, intern tables, glyph caches, and handle-based flyweights for memory-dense object systems.
BasicAdd reusable behavior via template base classes. CRTP mixins inject methods with zero overhead; C++23 deducing this offers a cleaner alternative.
Intermediate"The Pointer to Implementation idiom: ABI stability, compilation firewalls, and complete encapsulation using unique_ptr — with full Rule of 5 mechanics."
IntermediateInject behavior into class templates via policy parameters — compile-time Strategy with zero runtime overhead, composable across orthogonal concerns.
AdvancedIntercept operations on C++ objects to add logging, lazy loading, access control, or subscript read/write discrimination via proxy objects.
IntermediateHide concrete type identity behind a uniform interface without inheritance. Covers std::function, std::any, std::variant, Concept+Model wrappers, and SBO.
AdvancedBehavioral Patterns
Chain of Responsibility in C++ — linked handler chains, functional pipelines, middleware, and event bubbling with concrete patterns.
BasicEncapsulate operations as objects for deferred execution, undo/redo, queuing, and serialization — virtual hierarchies, std::function, and std::variant approaches.
BasicImplementing correct C++ iterators—forward, bidirectional, random access, and C++20 ranges-compatible with sentinel types.
IntermediateC++ mediator pattern — event bus, signal/slot, and classic coordinator implementations with unsubscription, re-entrancy safety, and thread considerations.
BasicCapture and restore object state in C++ without exposing internals — snapshots, undo/redo stacks, opaque mementos, and delta encoding.
BasicReplace nullptr returns and null checks with a do-nothing object that implements the full interface, eliminating guard code throughout callers.
BasicSignal/slot, event buses, and safe observer lifetime in C++ using std::function, RAII tokens, weak_ptr tracking, and C++20 concepts.
Intermediate"C++ state machine implementations: enum+switch, std::variant+std::visit (C++17), function tables, and coroutine-based sequential machines (C++20)."
IntermediateSwap algorithms at runtime or compile time without touching the context. Virtual dispatch, std::function, template policies, and C++20 concepts compared.
BasicDefine an algorithm's invariant skeleton in a non-virtual base-class method and defer variable steps to subclasses via NVI virtual hooks or CRTP for zero-overhead static dispatch.
BasicC++ visitor pattern — double dispatch, std::variant + std::visit, multi-variant dispatch, recursive ASTs, and the acyclic variant.
IntermediateC++-Specific Idioms
Implement exception-safe assignment by taking the argument by value, swapping internals with *this, and letting the old state destroy itself on scope exit.
IntermediateEncode arithmetic expression trees as nested types so chained operations compile to a single loop with no intermediate heap allocations.
AdvancedSimulate named function arguments in C++ using method-chaining builders, options structs, and C++20 designated initializers for self-documenting call sites.
BasicGrant selective access to private constructors and methods using an unforgeable token type, replacing coarse-grained friend declarations.
BasicPreserve value categories through template wrappers using forwarding references, std::forward, and reference collapsing.
IntermediateResource Acquisition Is Initialization — tie resource lifetime to object lifetime for deterministic, exception-safe cleanup with zero overhead.
BasicVirtual dispatch, std::variant+std::visit, type erasure, and std::function compared — heap cost, extensibility, performance, and when to reach for each.
IntermediateExecute cleanup code at scope exit regardless of how the scope is left — generalized RAII without a dedicated wrapper class.
BasicSelect function overloads at compile time by passing empty tag structs. The canonical pre-C++17 technique for type-based branching without SFINAE.
Intermediate"TypeList idiom: manipulate ordered sets of types at compile time with head/tail decomposition, filter, transform, and runtime dispatch patterns."
AdvancedOther Idioms
Use argument-dependent lookup to let generic algorithms discover type-specific overloads defined in a type's own namespace, enabling non-intrusive extensibility.
IntermediateSum types and product types in C++: composing data with std::variant, std::optional, and structs to make illegal states unrepresentable.
IntermediateInterpose a friend proxy class to grant selective, fine-grained access to a subset of another class's private members.
IntermediateInject non-template friend functions into a namespace via class template instantiation, discoverable exclusively through ADL at the point of use.
AdvancedGuarantee a member object is fully constructed before a dependent base class by promoting it into an earlier base class.
IntermediateSelecting function implementations or code paths at compile time using type traits, tag types, if constexpr, and concepts — with no virtual dispatch overhead.
IntermediatePass a callable representing "what happens next" into a function instead of returning a value, enabling composable async pipelines and stack-safe recursion.
IntermediateDefer expensive deep copies until a mutation is actually needed by sharing immutable state with a reference count and cloning only when a write occurs.
IntermediateA smart pointer idiom that tracks shared ownership via an atomic reference count, destroying the managed object when the last owner relinquishes it.
IntermediateCompile-time trait detection via SFINAE and void_t to test whether a type supports a given expression, member, or nested type.
AdvancedResolve a function call based on the runtime types of two objects, extending C++ virtual dispatch from one dimension to two.
AdvancedRemove elements from sequence containers by pairing std::remove/remove_if with erase, or use C++20's std::erase and std::erase_if for a cleaner one-liner.
BasicDesign pattern decoupling callable work from its execution context; formalized in C++26 as the scheduler/sender/receiver model in std::execution.
AdvancedDefine non-member functions as friend inside a class body so they are only visible via ADL, preventing implicit conversions and speeding up overload resolution.
IntermediateDefer expensive object construction or computation to first use, paying the cost only when the value is actually needed.
IntermediateCompose pipelines over std::optional and std::expected using and_then, transform, and or_else without manual value checks at each step.
IntermediateAll instances share state via static members (design pattern), and std::monostate is a C++17 unit type that makes variant default-constructible.
BasicFunction objects used in std::ranges algorithms that suppress ADL and behave as non-customizable algorithm entry points in C++20.
IntermediateA header-based reference-counting technique that guarantees a static object is initialized before any translation unit that includes its header uses it.
IntermediateA compile-time technique that merges multiple callables into a single object exposing all their operator() overloads via variadic using declarations.
IntermediateA typed handle to a specific non-static member of a class, invoked against any instance of that class using the .* and ->* operators.
IntermediateA proxy object with conversion operators lets one function produce different return types, selected implicitly by the assignment context.
IntermediateSubstitution Failure Is Not An Error — the compiler silently discards template specialisations whose type substitution produces an invalid expression, enabling fine-grained overload control.
AdvancedEmbed a fixed-size inline buffer inside an object to eliminate heap allocation for small payloads, trading object size for latency and cache locality.
AdvancedGuaranteeing exactly-once construction of a singleton across concurrent threads using function-local statics, std::call_once, or atomic DCLP.
AdvancedObjects with value semantics behave like built-in types—each copy is independent, mutations don't propagate across instances, and ownership is unambiguous.
BasicSimulate virtual behavior in non-member friend functions by delegating to a protected virtual member function.
Basic