CRTP可以完全替代较小设计的虚拟功能吗? [英] Can CRTP completely replace virtual functionality for smaller designs?

查看:208
本文介绍了CRTP可以完全替代较小设计的虚拟功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CRTP 足以胜过虚拟功能完全?

我看到的CRTP的唯一缺点是为每个重复模式生成的代码量很大。

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 ?

推荐答案

CRTP不提供运行时多态性。如果你需要运行时多态性,你需要虚拟方法。更糟糕的是,由于基类是模板化的,你甚至不能真正使用子类对象,因为它们与基类具有相同的类型,因为你不能将它们转换为基类 - 它不存在;它只是一个模板。

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.

我认为一个更有用的考虑多态性的方式 - 替换CRTP不是替代虚拟继承,而是一种混合形式。你不是在通常意义上制造子类;

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示例: mixin会像依赖 。这样的mixin可能包含指向该项所依赖的相同类型的其他项的指针列表;它会添加一个方法 register_dependency 添加一个依赖的对象, visit_dependents ?)拓扑顺序。另一个例子可以是本身包含 width height的任何东西添加 compute_area 方法。或任何...

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.

这篇关于CRTP可以完全替代较小设计的虚拟功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆