Multiple Dispatch in practice
Sergey Gromov
snake.scaly at gmail.com
Wed Oct 22 19:14:56 PDT 2008
Tue, 21 Oct 2008 22:01:15 -0400,
bearophile wrote:
> This is normal D1 code that shows a manual implementation of double dispatch:
>
> import std.stdio: writefln;
>
> /// ...
> template IsInstance(Class) {
> static assert(is(Class == class), "IsInstance: Class must be a class");
>
> bool IsInstance(TyObj)(TyObj obj) {
> return cast(Class)obj !is null;
> }
> }
>
> interface Vehicle {
> void collide(Vehicle v);
> }
>
> class Car : Vehicle {
> void collide(Vehicle v) {
> if (IsInstance!(Car)(v))
> writefln("Car hits car");
> else if (IsInstance!(Bike)(v))
> writefln("Car hits bike");
> else
> throw new Exception("missing case: should not happen");
> }
> }
>
> class Bike : Vehicle {
> void collide(Vehicle v) {
> if (IsInstance!(Car)(v))
> writefln("Bike hits car");
> else if (IsInstance!(Bike)(v))
> writefln("Bike hits bike");
> else
> throw new Exception("missing case: should not happen");
> }
> }
>
> void main() {
> Vehicle car = new Car();
> Vehicle bike = new Bike();
>
> car.collide(bike); // Car hits bike
> car.collide(car); // Car hits car
> bike.collide(car); // Bike hits car
> bike.collide(bike); // Bike hits bike
> }
You overcomplicate.
import std.stdio;
void main() {
Vehicle car = new Car();
Vehicle bike = new Bike();
car.collide(bike); // Car hits bike
car.collide(car); // Car hits car
bike.collide(car); // Bike hits car
bike.collide(bike); // Bike hits bike
}
interface Vehicle {
void collide(Vehicle v);
void onCollision(Car c);
void onCollision(Bike b);
}
class Car : Vehicle {
override void collide(Vehicle v) {
v.onCollision(this);
}
override void onCollision(Car c) {
writefln("Car hits car");
}
override void onCollision(Bike b) {
writefln("Bike hits car");
}
}
class Bike : Vehicle {
override void collide(Vehicle v) {
v.onCollision(this);
}
override void onCollision(Car c) {
writefln("Car hits bike");
}
override void onCollision(Bike b) {
writefln("Bike hits bike");
}
}
More information about the Digitalmars-d
mailing list