How to prohibit implicit conversion to base class?

I would like to clearly distinguish between 3D and 2D points in my code. The obvious solution would be to have separate classes.

On the other hand, transformations from three-dimensional points with z = 0 to two-dimensional points are quite common. Therefore, I would like to use a common base class so that I can do these transformations in place in memory. To clearly distinguish between types, I would like to prohibit implicit conversion to this base class. Is this doable?

Or maybe there is another way to create different types with a similar function?

+5
source share
4 answers

If you want to access the 2nd part of your 3D vector without copying, there really is only one sensible solution.

class Vector2d { ... };
class Vector3d {
    Vector2d part2d;
    double z;
public:
    Vector2d& as2d() { return part2d; }
};

shenanigans, , , undefined .

+1

, 3D-, 2D- .

+2

:

class PointBase {
  // ...
};

class Point2D : private PointBase {
  // ...
};

class Point3D : private PointBase {
  // ...
};

, PointBase , , -, using. , PointBase , .

+2

If your point is stored as a vector, you can define your 3D and 2D point classes as template classes with a parameter intthat will indicate the dimension of the counter:

template<int dimensions> class Point {
    vector<int> coords;
    Point() : coords(dimensions) {}
    ....
    template<int other_dimensions> convertToPoint() const
    {
        // Handle different options here like:
        //   dimensions > other_dimensions
        //   dimensions < other_dimensions
        // et cetera
    }
};

And instantiate the point classes:

typedef Point<2> Point2D;
typedef Point<3> Point3D;
Point2D pt = Point3D(1, 2, 3).convertToPoint<2>(); // Point2D(1, 2);
Point3D pt = Point2D(4, 5).convertToPoint<2>(); // Point3D(4, 5, 0);

This way you will have the same logic, but completely different types and simple conversions. Not to mention that you will need to define only one class instead of two separate ones.

+1
source

All Articles