C++ Multiple Dispatch?

I clearly must be missing something. I just noticed this article on the O'Reilly ONLamp blog, discussing multiple dispatch in Perl.

The example code given:

class Thing             {}
class Rock     is Thing {}
class Paper    is Thing {}
class Scissors is Thing {}

multi sub defeats(Thing    $t1, Thing    $t2) { 0 };
multi sub defeats(Paper    $t1, Rock     $t2) { 1 };
multi sub defeats(Rock     $t1, Scissors $t2) { 1 };
multi sub defeats(Scissors $t1, Paper    $t2) { 1 };

my $paper = Paper.new;
my $rock  = Rock.new;

say defeats($paper, $rock);
say defeats($rock, $paper);

Absolutely, positively translates directly into C++:

#include <iostream>

class Thing{};
class Rock  : public Thing {};
class Paper : public Thing {};
class Scissors : public Thing {};

bool defeats(const Thing &, const Thing &) { return false; }
bool defeats(const Paper &, const Rock &) { return true; }
bool defeats(const Rock  &, const Scissors &) { return true; }
bool defeats(const Scissors &, const Paper &) { return true; }

Paper paper;
Rock rock;

int main(int, char **)
  std::cout << std::boolalpha;
  std::cout << defeats(paper, rock) << std::endl;
  std::cout << defeats(rock, paper) << std::endl;

Is multiple dispatch nothing more than just function overloading?


paper and rock have to be declared as type Thing* in order for the problem/difference to show up in C++ (or Java). Overloading is resolved at compile time, so if you switch the compile-time types, you switch which function gets called.

I see that now, after looking at the linked documents. But the specific example in the ONLamp article does not clearly show that, nor does it even give a compelling case for why you would want to use runtime dispatch instead of compile time, except, I guess "compile time" doesn't really exist in Perl?

I threw together a quick C++ example of how one would do runtime function dispatch in C++.

C++ Multiple Dispatch!