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
{
}
};
And instantiate the point classes:
typedef Point<2> Point2D;
typedef Point<3> Point3D;
Point2D pt = Point3D(1, 2, 3).convertToPoint<2>();
Point3D pt = Point2D(4, 5).convertToPoint<2>();
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.
source
share