Created
July 25, 2012 11:28
-
-
Save thomie/3175639 to your computer and use it in GitHub Desktop.
Double dispatch in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
/* Forward declarations. */ | |
class Structure; | |
class Plane; | |
class Cylinder; | |
void print2(Cylinder*, Plane*); | |
void print2(Plane*, Cylinder*); | |
void print2(Cylinder*, Cylinder*); | |
void print2(Plane*, Plane*); | |
class Structure { | |
public: | |
virtual void print(Structure* target) {}; | |
virtual void print_helper(Plane* origin) {}; | |
virtual void print_helper(Cylinder* origin) {}; | |
}; | |
class Plane : public Structure { | |
public: | |
Plane() : name("Plane") {}; | |
virtual void print(Structure* target) { | |
printf("Plane::print --- "); | |
target->print_helper(this); | |
} | |
virtual void print_helper(Plane* origin) { | |
::print2(origin, this); | |
} | |
virtual void print_helper(Cylinder* origin) { | |
::print2(origin, this); | |
} | |
const char* name; | |
}; | |
class Cylinder : public Structure { | |
public: | |
Cylinder() : name("Cylinder") {}; | |
virtual void print(Structure* target) { | |
printf("Cylinder::print --- "); | |
target->print_helper(this); | |
} | |
virtual void print_helper(Plane* origin) { | |
::print2(origin, this); | |
} | |
virtual void print_helper(Cylinder* origin) { | |
::print2(origin, this); | |
} | |
const char* name; | |
}; | |
void print2(Cylinder* c, Plane* p) { | |
printf("%s %s\n", c->name, p->name); | |
} | |
void print2(Plane* p, Cylinder* c) { | |
printf("%s %s\n", p->name, c->name); | |
} | |
void print2(Cylinder* c1, Cylinder* c2) { | |
printf("%s %s\n", c1->name, c2->name); | |
} | |
void print2(Plane* p1, Plane* p2) { | |
printf("%s %s\n", p1->name, p2->name); | |
} | |
int main(void) { | |
Plane p; | |
Cylinder c; | |
Cylinder* c_ptr = &c; | |
Plane* p_ptr = &p; | |
printf("*** Single dispatch ***\n"); | |
c.print_helper(p_ptr); | |
p.print_helper(c_ptr); | |
c.print_helper(c_ptr); | |
p.print_helper(p_ptr); | |
printf("*** Double dispatch ***\n"); | |
c.print((Structure *) p_ptr); | |
p.print((Structure *) c_ptr); | |
c.print((Structure *) c_ptr); | |
p.print((Structure *) p_ptr); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment