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.
you're adding premade functionality to your class
, can you elaborate more ? – Khedive