如何使现有的类成为类模板?

use*_*020 -1 c++ templates c++11

例如,我有几个现有的2D(二维)和3D情况的点类,比如class Point2Dclass Point3D.我希望它是模板像template<int D> class Point这里Point<2>相当于或直接使用Point2DPoint<3>等同于或直接使用Point3D.我不想重新实现那些现有的类,因为我的真正的类不像类点那么简单,它是第三方代码,比如

using Point<2> = Point2D;
using Point<3> = Point3D;
Run Code Online (Sandbox Code Playgroud)

有办法吗?

Que*_*tin 8

当然!不要修改类,而是添加typedef:

template <int D>
struct pointType_;

template <>
struct pointType_<2> { using type = Point2D; };

template <>
struct pointType_<3> { using type = Point3D; };

template <int D>
using Point = typename pointType_<D>::type;
Run Code Online (Sandbox Code Playgroud)