Can CRTP completely replace virtual functionality for smaller designs?
Asked Answered
K

2

3

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 ?

Khedive answered 7/7, 2011 at 16:18 Comment(0)
C
17

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.

Charlatan answered 7/7, 2011 at 16:23 Comment(1)
you're adding premade functionality to your class, can you elaborate more ?Khedive
I
1

Use whichever makes the design more clear and is easier to code/maintain. Unless you have a significant measured performance/space reason to pick one or the other, it's almost always better to just use the easiest way to code/debug/maintain.

With CRTP you have to have more template methods so it can act on the proper base class, which may or may not be a downside.

Idaidae answered 7/7, 2011 at 16:22 Comment(1)
Isn't CRTP always an easier option, as it is templatized and less error prone ?Khedive

© 2022 - 2024 — McMap. All rights reserved.