Question

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

Was it helpful?

Solution

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));
  }
}

OTHER TIPS

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.

(updated to match updated question)

To avoid duplication move your conversion code in one helper function and let C++ do the rest of the work:

geometry makeg(Geom_Object_t* g) {
    switch(g->type) {
         case TYPE_POINT: return Point(g->geom.p.x, g->geom.p.y);
         case TYPE_LINE : return Line(g->geom.l.x, g->geom.l.y, g->geom.l.slope_x, g->geom.l.slope_y);
         // ...
    }
}

makeg(geom1).distanceTo(makeg(geom2));

could you do something simple like:

if (g1->type == LINE) {
  if (g2->type == LINE) return g1->distance(g2->l);
  if (g2->type == POINT) ...
}
else ...

you can implement this part in C++ and expose the function through the extern "C"

then you could perhaps provide a method in your geometrical classes to accept geometrical struct as a parameter and perform dispatching inside the classes using regular C++ function overload.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top