Is CRTP capable enough to outsmart virtual
functionality completely ?
Th开发者_如何学编程e 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 ?
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.
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.
精彩评论