你想要的是一个函数,它不仅在第一个参数上分派,而且在第二个参数上分派,即双重分派。这在 C++ 中不直接支持,但可以模拟。
class Point;
class Line;
class Collider {
public:
virtual bool Collides(Collider const& x) const = 0;
protected:
virtual bool Collides(Point const& p) const = 0;
virtual bool Collides(Line const& l) const = 0;
friend class Point;
friend class Line;
};
class Point: public Collider {
public:
virtual bool Collides(Collider const& x) const {
// here, the type of this is now Point
// now, find out what x is and call the overload on this type
return x.Collides(*this);
}
protected:
virtual bool Collides(Point const& p) const {
return false;
// we now know that we are a point and checking vs. another point
}
virtual bool Collides(Line const& l) const {
return false;
// we now know that we are a point and checking vs. a line
}
};
class Line: public Collider {
public:
virtual bool Collides(Collider const& x) const {
// here, the type of this is now Line
return x.Collides(*this);
}
protected:
virtual bool Collides(Point const& p) const {
return false;
// we now know that we are a line and checking vs. a point
}
virtual bool Collides(Line const& l) const {
return false;
// we now know that we are a line and checking vs. another line
}
};
现在,检查两个对象将执行两个运行时调度:
Collider* p = new Point();
Collider* l = new Line();
p->Collides(*l);
// first dynamically dispatches on p to call Point::Collides
// in Collides, this (which is p) now has the static Point.
// now do the second dispatch on l and use *this as the parametet
// to find the overload.
这例如用在访问者设计模式中。如果您的对象集是固定的,但您希望对它们执行的操作会更改或扩展,那么 Visitor 是一个不错的选择。