Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can CRTP completely replace virtual functionality for smaller designs?

Is CRTP capable enough to outsmart virtual functionality completely ?

The only disadvantage I see with CRTP is notable amount of code generated for every recurring pattern. For smaller designs, (where 2-3 classes are derived from a base), is CRTP a better idea ?

like image 622
iammilind Avatar asked Dec 03 '25 10:12

iammilind


1 Answers

CRTP does not provide runtime polymorphism. If you need runtime polymorphism, you need virtual methods. Worse, since the base class is templated, you can't even really use the subclass objects as if they were of the same type as the base class since you can't cast them to that base class — it doesn't exist; it's just a template.

I think a more useful way of thinking about polymorphism-replacing CRTP is not as a replacement for virtual inheritance, but rather as a form of mixins. You aren't making subclasses in the usual sense; instead, you're adding pre-made functionality to your class.

Mixin example: an example of a mixin would be something like depends-on. Such a mixin might contain a list of pointers to other items of the same type on which this item depends; it'd add a method register_dependency that adds an object it depends on and visit_dependents which visits all its dependencies in (reverse?) topological order. Another example could be something that adds a compute_area method to anything which itself contains width and height methods. Or whatever...

If you think of it as a replacement for a type hierarchy, you're just making harder to comprehend, harder to debug code that doesn't quite work the way it should. Unless you really need the performance gain (if any — not guaranteed), this sounds like a bad idea. If you're doing it to quickly glue on some extra bits but without the conceptual weight of inheritance, I'd say you're fine — "Real" inheritance isn't necessary that frequently anyhow.

like image 188
Eamon Nerbonne Avatar answered Dec 05 '25 00:12

Eamon Nerbonne