0

I have the following simple classes which model sets of points.

struct Shape
{
    virtual bool contains(point x) const = 0;
}
typedef std::shared_ptr<Shape> ShapePtr;

struct Intersection : public Shape
{ 
    Intersection(ShapePtr shape1, ShapePtr shape2):
                 shape1_(shape1),shape2_(shape2){}
    ShapePtr shape1_;
    ShapePtr shape2_;
    bool contains(point x) const {return shape1_->contains(x) && 
                                         shape2_->contains(x);}
}

ShapePtr intersect(ShapePtr shape1, ShapePtr shape2)
{
    return std::make_shared<Intersection>(shape1, shape2);
}

so far so good. But suppose that I add a Shape that is a Rectangle:

struct Rectangle : public Shape 
{
     double x1_,x2_,y1_,y2_;
     ...
}

The original code works fine, but it can be improved using the fact that the intersection of two rectangles is a rectangle. That is, the intersect function could return a pointer pointing to a Rectangle.

How should I modify this code to accommodate for more such situations when I add more complicated shapes?

Martin Drozdik
  • 12,742
  • 22
  • 81
  • 146

1 Answers1

1

You probably want MultiMethods. Specifically, you want runtime-dispatch on actual type.

Here's a post about them: "type-switch" construct in C++11

BTW: As you are always using std::shared_ptr with all objects derived from Shape, consider using std::enable_shared_from_this.

Also, you might want to create a bounding box and check for empty intersection. As an added optimisation, add an empty shape (static Singleton object). Shape itself is a good type for it.

Community
  • 1
  • 1
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • Thank you for all the useful advice! I am trying to understand the solution you gave me. You seem to have experience in this kind of thing. Is there some opensource library with similar code that I can study? – Martin Drozdik Apr 23 '14 at 19:35
  • So you suggest that I modify the `intersect` function each time I add an optimization on some particular combination of shapes? – Martin Drozdik Apr 23 '14 at 19:37
  • I don't know any. I'm just applying OO mantra and concepts imported to static-land from dynamic languages. – Deduplicator Apr 23 '14 at 19:39
  • AFAIK, there is no way in C++ to get a list of all overloads a function has for template meta-programming. That would enable you to keep the source-code of the `intersect`-function the same, though it would not change the need for recompiling. BTW: I would always get `Shape*`-arguments for `intersect`, after you integrated `enable_shared_from_this` – Deduplicator Apr 23 '14 at 19:42