Static Polymorphism
Compile time polymorphism.
1. Introduction
Static polymorphism in C++ is achieved using templates and compile-time mechanisms. Unlike dynamic polymorphism (achieved with inheritance and virtual functions), static polymorphism determines which function to call at compile time, resulting in better performance because there is no runtime overhead like virtual table lookups.
The most common method to achieve static polymorphism in C++ is through templates and CRTP (Curiously Recurring Template Pattern).
2. CRTP(Curiously Recurring Template Pattern)
CRTP is a design pattern where a derived class inherits from a base class that is templated on the derived class. This allows compile-time polymorphism with no runtime overhead.
1 |
|
Here is a more generic example.
1 |
|
3. Comparison with Dynamic Polymorphism
Feature | Static Polymorphism | Dynamic Polymorphism |
---|---|---|
Binding Time | Compile-time | Runtime |
Implementation | Templates, CRTP | Virtual functions, inheritance |
Performance | Faster (no vtable lookup) | Slower due to runtime overhead |
Flexibility | Limited (known types at compile time) | Flexible (can use any derived type at runtime) |
4. Conclusion
You should use static polymorphism when:
- You need polymorphism but want to avoid the overhead of dynamic dispatch.
- In scenarios where the type of objects involved is known at compile-time.
- Your system is performance-critical.
Static Polymorphism
http://chuzcjoe.github.io/2024/11/24/cpp-static-polymorphism/