int
ポイントがベクトルとして保存されている場合、次元数を指定するパラメーターを使用して、3D および 2D ポイント クラスをテンプレート化されたクラスとして定義できます。
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
}
};
そして、ポイント クラスをインスタンス化します。
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);
このようにして、同じロジックを使用できますが、完全に異なる型と簡単な変換が得られます。言うまでもなく、2 つの別個のクラスではなく、1 つのクラスのみを定義する必要があります。