多种调度、多种方式
它们是什么,它们之间有什么不同?
许多来源,例如维基百科,声称它们是同一件事,但其他人明确表示相反,就像这个问题中的sbi:
第一:“访问者模式是一种在 C++ 中模拟双重调度的方法。”呃,这并不完全正确。实际上,双重分派是多重分派的一种形式,它是一种在 C++ 中模拟(缺失的)多方法的方法。
What are they, what's the different between them?
Many sources, like Wikipedia, claim they're the same thing, but others explicitly say the opposite, like sbi in this question:
First: "Visitor Pattern is a way to simulate Double Dispatching in C++." This is, erm, not fully right. Actually, double dispatch is one form of multiple dispatch, which is a way to simulate (the missing) multi-methods in C++.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
他们是一样的。
当您在 C++ 中调用虚拟方法时,要运行的实际方法取决于调用该方法的对象的运行时类型。这称为“单一调度”,因为它取决于单个参数的类型(在本例中为隐式“this”参数)。例如,以下内容:
运行时,上述程序打印 123,而不是 3。到目前为止一切顺利。
多重分派是语言或运行时分派“this”指针类型和方法参数类型的能力。考虑一下(暂时坚持使用 C++ 语法):
如果 C++ 具有多重分派,程序将打印出“Called Derived::Foo with a Dervied*”。 (遗憾的是,C++ 没有多重分派,因此程序会打印出“Called Derived::Foo with a Base*”。)
双重分派是多重分派的一种特殊情况,通常更容易模拟,但也不是很可怕。作为一种语言特征很常见。大多数语言要么进行单次分派,要么进行多次分派。
They are the same.
When you call a virtual method in C++, the actual method to run is based on the runtime type of the object them method is invoked on. This is called "single dispatch" because it depends on the type of a single argument (in this case, the implicit 'this' argument). So, for example, the following:
When run, the above program prints 123, not 3. So far so good.
Multiple-dispatch is the ability of a language or runtime to dispatch on both the type of the 'this' pointer and the type of the arguments to the method. Consider (sticking with C++ syntax for the moment):
If C++ had multiple-dispatch, the program would print out "Called Derived::Foo with a Dervied*". (Sadly, C++ does not have multiple-dispatch, and so the program prints out "Called Derived::Foo with a Base*".)
Double-dispatch is a special case of multiple-dispatch, often easier to emulate, but not terribly common as a language feature. Most languages do either single-dispatch or multiple-dispatch.