Reply to comment

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?

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • Lines and paragraphs break automatically.
  • You may post PHP code. You should include <?php ?> tags.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.