C++ Design Patterns: Beyond Virtual Functions and Inheritance
0:00:02 Introduction: This talk focuses on design patterns in C++, addressing misconceptions and exploring alternatives to virtual functions.
0:00:38 Curiously Recurring Template Pattern (CRTP): Introduced in 1995, CRTP involves a base class template where derived classes pass themselves as template parameters, enabling static polymorphism.
0:02:41 CRTP Functionality: CRTP avoids virtual functions by using static casts within the base class to call derived class methods, leading to potential performance improvements.
Each derived type has a different base class, preventing common base class usage (e.g., std::vector<Animal>).
Using CRTP extensively leads to a template-heavy codebase, moving functionality to header files and potentially creating a "template header-only library."
0:09:34 Deducing this: In C++23, explicit object parameters offer a simpler alternative to CRTP in some cases by deducing the type of the this object.
0:11:52 CRTP vs. Deducing this: Deducing this cannot replace CRTP when the base class needs to access derived class methods.
0:16:39 Clarifying CRTP Terminology: Two distinct forms of CRTP exist:
Static Interface: A design pattern using CRTP to define a common interface for a family of related types.
Mixin: An implementation detail using CRTP to inject functionality into a derived class, not a design pattern.
0:20:28 Replacing CRTP with Concepts (C++20): Concepts can potentially replace CRTP's static interface form, but care must be taken to avoid unintended duck typing.
0:24:47std::variant: Explores std::variant as an alternative to inheritance and virtual functions, offering a functional approach to polymorphism.
0:34:38 Modernizing the Code with std::variant: The example demonstrates replacing inheritance with std::variant, resulting in a simpler design with value semantics and no manual memory management.
0:39:44 Performance: Benchmarks suggest that std::variant can offer performance benefits over virtual functions in specific scenarios, but results may vary.
0:42:52 Architectural Considerations: Using std::variant extensively can lead to architectural issues, such as tight coupling and difficulty in separating concerns.
0:47:27 Templates as a Solution?: While templates can help address some std::variant limitations, they can also lead to a template-heavy codebase.
0:48:17std::variant vs. Virtual Functions:std::variant and virtual functions are fundamentally different and not directly interchangeable. std::variant offers a closed set of types and an open set of operations, while virtual functions provide the opposite.
0:52:03 Design First, Implementation Second: Emphasizes the importance of choosing an architectural design before focusing on implementation details like specific patterns or performance.
0:52:56 Q&A: Discussion about design pattern choices and performance.