Extending struct with type erasure apprach to avoid major refactoring

84 Views Asked by At

I am writing from existing (not my) code. It uses Path (i.e. using Path = std::vector<Point>;) everywhere. Point has no functionality. It just stores data. One of the methods takes Path, filters out the points, and returns a new Path.

Path filter(cosnt Path& path) {... return filteredPath; }

During filtering, I want to add additional information describing the point (such as how the point was calculated). So, I want to have something like PointExt : Point (there are might be additional types). Doing so will require me to change to using Path = std::vector<std::unique_ptr<Point>> and change code in many places. I'm thinking of using type erasure instead. Thus, I can change only in places where I really need to cast to PointExt and get the extra information.

By doing so I thought I could keep the current usage of adding Point to Path and I could also add PointExt.

Path path;
path.push_back(Point());
path.push_back(PointExt());

I converted Point to type erasure as shown below and defined PointExt : Point. But, I get attempting to reference a deleted function error.

  1. What am I doing wrong?
  2. Is my solution a reasonable way to solve this problem or is it ridiculous?

CODE

struct Point
{
    template<typename T>
    Point(T&& p): object(std::make_shared<Model<T>>(std::forward<T>(p))) {}

    virtual PointType getType() const { return object->getType(); }
  
    struct Concept
    {
        virtual ~Concept() {}
        virtual PointType getType() const = 0;
    };

    template<typename T>
    struct Model : Concept
    {
        Model(const T& t) : object(t) {}
        T object;
        PointType getType() const override { return object.getType(); }
    };

    int x;
    int y;
    std::shared_ptr<Concept> object;
};

struct PointExt : Point
{
   PointType getType() const override { return PointType::PointExt ; }
    
   std::vector<Solution> solutions;
};

struct PointExt2 : Point
{
   PointType getType() const override { return PointType::PointExt2 ; }
    
   ...
};

UPDATE

I found the reason for the error attempting to reference a deleted function . I forgot default constructor in Point. So, once I added Point() = default; it fixed the error.

0

There are 0 best solutions below