具有两个可以采用多种不同类型的操作数的虚函数
让我从一个具体的例子开始。在 C++ 中,我在抽象基类 CollisionVolume
下有一个类层次结构。任何碰撞体积都需要能够检测与任何其他体积的碰撞。该碰撞代码是基于存在的两个子类而专门化的,但它是可交换的:detectCollision(a, b) == detectorCollision(b, a)
。
我需要使用类似于虚函数的机制,因为对象通常属于抽象基类。但是,如果我使用典型的虚拟方法,则所选函数只能取决于其中一个操作数的类型,而不取决于两者的类型。我能够做到这一点的唯一方法是使用 RTTI 或类似 RTTI 的机制。
有没有更干净的方法来做到这一点?
Let me start with a concrete example. In C++, I have a hierarchy of classes under the abstract base class CollisionVolume
. Any collision volume needs to be able to detectCollision
with any other volume. This collision code is specialized based on the two subclasses in presence, but it is commutative: detectCollision(a, b) == detectCollision(b, a)
.
I need to use a mechanism similar to virtual functions since the objects will typically be of the abstract base class. However, if I use typical virtual methods, the chosen function can only depend on the type of one of the operand, not both. The only way I was able to do this is using RTTI or an RTTI-like mechanism.
Is there any cleaner way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在寻找多重调度。 C++没有它,因为它很难有效地实现。大多数其他静态类型/面向效率的语言也没有。您的 RTTI 解决方案可能是伪造它的最佳方法。
You're looking for multiple dispatch. C++ doesn't have it because it's hard to implement efficiently. Most other statically typed/efficiency-oriented languages don't either. Your RTTI solution is probably about the best way of faking it.
有多种解决方案可以在 C++ 中模拟多方法。
这里有一些可以帮助您解决问题的参考文献:
S.Meyers“更有效的 C++< /a>”,第 31 条:使函数对于多个对象而言是虚拟的。
A.Alexandrescu“现代 C++ 设计”,第 11 章。多种方法
C++ 中的多种方法:寻找完整的解决方案作者:Danil Shopyrin
多重调度。使用模板和 RTTI 的新方法,作者:Carlo Pescio 博士,C++ 报告,1998 年 6 月。
向 C++ 添加多方法的提案草案,此处 和 此处
There are several solutions to emulate multimethods in C++.
Here some references that can helps you to solve your problem:
S.Meyers "More effective C++", Item 31: Making functions virtual with respect to more than one object.
A.Alexandrescu "Modern C++ design", Chapter 11. Multimethods
MultiMethods in C++: Finding a complete solution by Danil Shopyrin
Multiple Dispatch. A new approach using templates and RTTI by Dr. Carlo Pescio, C++ Report, June 1998.
Draft proposal for adding Multimethods to C++, here and here
我最初的想法是,在阅读后似乎是访问者模式(?)返回有关对象的一些重要信息的虚拟函数,然后在
detectCollision()
中比较两个对象返回的重要信息。这样,每个对象都可以返回专门的信息,但可以以通用的方式对它们进行比较。这可能不是最有效的方法,但看起来相对简单。
My initial idea, which upon reading appears to be the visitor pattern(?), is to make a virtual function that returns some vital information about the object, then, in
detectCollision()
, compare the vital information returned by the two objects. That way, each object can return specialized information, but they can be compared in a generalized way.This may not be the most efficient way of doing it, but it seems relatively simple.