Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple dispatch in C++

I am trying to understand what multiple dispatch is. I read a lot of various texts but I still have no idea what multiple dispatch is and what it is good for. Maybe the thing I am missing is piece of code using multiple dispatch. Please, can you write a little piece of code in C++ using multiple dispatch so that I can see it cannot be compiled/runned properly because C++ has only single dispatch? I need to see the difference. Thanks.

like image 541
Martin Avatar asked Nov 17 '09 15:11

Martin


People also ask

What is multiple dispatch in programming?

Multiple dispatch is a programming concept that allows a programmer to write a function multiple times to handle different types. A lot of programmers tend to stray far away from the functional programming paradigm for its global scope.

Why is multiple dispatch good?

Multiple dispatch is a simple concept: Functions can have multiple definitions as long as each definition restricts the types of the arguments differently. It is perhaps one of the best features of the Julia language.

What is multiple dispatch in Julia?

Using all of a function's arguments to choose which method should be invoked, rather than just the first, is known as multiple dispatch.


1 Answers

Multi-dispatch is the ability to choose which version of a function to call based on the runtime type of the arguments passed to the function call.

Here's an example that won't work right in C++ (untested):

class A { }; class B : public A { }; class C : public A { }   class Foo {   virtual void MyFn(A* arg1, A* arg2) { printf("A,A\n"); }   virtual void MyFn(B* arg1, B* arg2) { printf("B,B\n"); }   virtual void MyFn(C* arg1, B* arg2) { printf("C,B\n"); }   virtual void MyFn(B* arg1, C* arg2) { printf("B,C\n"); }   virtual void MyFn(C* arg1, C* arg2) { printf("C,C\n"); } };  void CallMyFn(A* arg1, A* arg2) {   // ideally, with multi-dispatch, at this point the correct MyFn()    // would be called, based on the RUNTIME type of arg1 and arg2   pFoo->MyFn(arg1, arg2); }  ...  A* arg1 = new B(); A* arg2 = new C(); // Using multi-dispatch this would print "B,C"... but because C++ only // uses single-dispatch it will print out "A,A" CallMyFn(arg1, arg2); 
like image 144
Aaron Avatar answered Sep 19 '22 18:09

Aaron