Suppose I have something like the following:
class Point : geometry {
...
Point(double x, double y) {
}
double distanceTo(Line) {
}
double distanceTo(Point) {
}
}
class Line : geometry {
...
Line(double x, double y, double slopex, double slopey) {
}
double distanceTo(Line) {
}
double distanceTo(Point) {
}
}
struct point_t {
double x, y;
}
struct line_t {
double x, y, slope_x, slope_y;
}
struct Geom_Object_t {
int type;
union {
point_t p;
line_t l;
} geom;
}
I am wondering what the best way to define a dispatch table for a function like
double distanceTo(Geom_Object_t * geom1, Geom_Object_t * geom2) {
}
The classes are written in C++, but the distanceTo function and the struct must be externed to C
thanks
I would make the class diagram different: an abstract base class GeomObject, subclassing geometry (with a getType accessor, as well as pure virtual distanceTo overloads), and concrete subclasses Line and Point of GeomObject (with overrides of the accessor and overloads). The need to "extern C" the double distanceTo function is not a problem, since you're not talking about overloads of that function anyway: you simply want to return geom1.distanceTo(x) (letting the virtual table do that part of the work;-) where x is an appropriate cast, e.g., assuming the class diagram I've explained:
extern "C"
double distanceTo(Geom_Object_t * geom1, Geom_Object_t * geom2) {
if(geom2->getType() == POINT_TYPE) {
return geom1->distanceTo(static_cast<Point*>(geom2));
} else {
return geom1->distanceTo(static_cast<Line*>(geom2));
}
}
I would use double dispatch with Visitor pattern. Then you only have to have two pointers to geometry objects and let double dispatch call the appropriate virtual distanceTo function based on actual dynamic types of two objects, which you can do from your C function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With