oop - Multiple dispatch and multi-methods -
what they, what's different between them?
many sources, wikipedia, claim they're same thing, others explicitly opposite, sbi in this question:
first: "visitor pattern way simulate double dispatching in c++." is, erm, not right. actually, double dispatch 1 form of multiple dispatch, way simulate (the missing) multi-methods in c++.
they same.
when call virtual method in c++, actual method run based on runtime type of object them method invoked on. called "single dispatch" because depends on type of single argument (in case, implicit 'this' argument). so, example, following:
class base { public: virtual int foo() { return 3; } } class derived : public base { public: virtual int foo() { return 123; } } int main(int argc, char *argv[]) { base* base = new derived; cout << "the result " << base->foo(); delete base; return 0; } when run, above program prints 123, not 3. far good.
multiple-dispatch ability of language or runtime dispatch on both type of 'this' pointer and type of arguments method. consider (sticking c++ syntax moment):
class derived; class base { public: virtual int foo(base *b) { cout << "called base::foo base*"; } virtual int foo(derived *d) { cout << "called base::foo derived*"; } } class derived : public base { public: virtual int foo(base *b) { cout << "called derived::foo base*"; } virtual int foo(derived *d) { cout << "called derived::foo derived*"; } } int main(int argc, char *argv[]) { base* base = new derived; base* arg = new derived; base->foo(arg); delete base; delete arg; return 0; } if c++ had multiple-dispatch, program print out "called derived::foo dervied*". (sadly, c++ not have multiple-dispatch, , program prints out "called derived::foo base*".)
double-dispatch special case of multiple-dispatch, easier emulate, not terribly common language feature. languages either single-dispatch or multiple-dispatch.
Comments
Post a Comment