Middle+
What is the name of the static polymorphism idiom in C++?
sobes.tech AI
Answer from AI
Curiously Recurring Template Pattern (CRTP), also known as static polymorphism or compile-time polymorphism.
The CRTP principle is based on the fact that a template class Base uses itself as a template parameter, while being a base class for some derived class Derived.
template <typename T>
class Base
{
public:
void interfaceMethod()
{
// Static call to 'implementationMethod'
// on an object of type Derived (which is T)
static_cast<T*>(this)->implementationMethod();
}
// Virtual method is not needed here
};
class Derived : public Base<Derived>
{
public:
void implementationMethod()
{
// Implementation specific to Derived
// ...
}
};
Advantages of CRTP over dynamic polymorphism (with virtual functions):
- Performance: Function calls are static and resolved at compile time, avoiding virtual table overhead.
- No overhead for virtual functions: No need to store and use vptr/vtbl.
- Stricter type checking: Errors related to type mismatch or missing implementation are detected at compile time.
Disadvantages:
- Need to know the derived type: The base class must be a template and "know" the derived class type.
- Complexity for beginners: The pattern can be less intuitive compared to classic inheritance with virtual functions.
- Cannot work with a collection of different CRTP types: You cannot store objects of different derived CRTP classes in one container and call them through a base pointer/reference.
Comparison with dynamic polymorphism:
| Aspect | CRTP (static polymorphism) | Dynamic polymorphism (virtual functions) |
|---|---|---|
| Call resolution | Compile time | Runtime |
| Performance | Higher (no vtbl overhead) | Lower (has vtbl overhead) |
| Overhead | No vptr/vtbl | Has vptr/vtbl |
| Flexibility (collections) | No (cannot work with heterogeneous types via a common base pointer/reference) | Yes (can work with heterogeneous types) |
| Error detection | Compile time | Runtime |
| Complexity | Higher for beginners | Lower for beginners |