Dispatch table in C ++

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 is the best way to define a distribution table for a function like

double distanceTo(Geom_Object_t * geom1, Geom_Object_t * geom2) {
}

Classes are written in C ++, but the distanceTo function and structure must be externed in C

thank

+3
source share
4 answers

: GeomObject, geometry ( getType, distanceTo) Line Point GeomObject ( ). "extern C" double distanceTo , : geom1.distanceTo(x) ( ;), x , , , :

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

. geometry distanceTo, , C.

+2

(, )

, ++ :

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));
+1

- :

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

++ extern "C"

then you could provide a method in your geometric classes to accept the geometric structure as a parameter and dispatch within classes using regular C ++ function overloading.

0
source

Source: https://habr.com/ru/post/1728708/


All Articles