我得到了以下信息:
template<typename T> class CVector3
{
CVector3<T> &normalize();
// more stuff
};
typedef CVector3<float> Vector3f;
typedef CVector3<double> Vector3d;我主要想添加一个方法toPoint(),如果为T=float,则返回一个结构Point3f,如果为T=double,则返回一个结构Point3d。我尝试将这两个typedefs替换为:
class Vector3f: public CVector3<float>
{
Point3f toPoint() const;
};
class Vector3d: public CVector3<double>
{
Point3d toPoint() const;
};然而,这不起作用,因为现在normalize()被破坏了:它不再返回一个Vector3f,而是一个与Vector3f不兼容的CVector3,因为它实际上是基类。我可以在基类中添加normalize()和任何其他公共方法的包装器方法,但我不想这样做,因为这会使维护这些类变得单调乏味。
我还尝试将typedefs放回模板定义中,并在模板定义之外添加:
template<>
Point3f CVector3<float>::toPoint() const;
template<>
Point3d CVector3<double>::toPoint() const;这不会编译,因为toPoint()没有在模板定义中声明。我不能把它放进去,因为返回类型是Point3f/Point3d。
我该怎么做呢?任何帮助都是非常感谢的!
发布于 2013-07-12 21:56:17
感谢你的回复,我现在已经想出了一个可行的方法:
template<typename T, typename P> class CVector3
{
CVector3<T, P> &normalize();
// more stuff
P toPoint() const;
};
typedef CVector3<float, Point3f> Vector3f;
typedef CVector3<double, Point3d> Vector3d;我将尝试一下,并在稍后告诉您它是否有效。干杯!
编辑:是的,它起作用了!我不得不这样定义toPoint():
template<>
Point3f CVector3<float, Point3f>::toPoint() const
{
Point3f pt = { x, y, z };
return pt;
}您对特征的回答当然是一个更通用的解决方案,但是由于Point3f是Vector3f的天然挂件,所以我更喜欢第二个模板参数。
发布于 2013-07-12 21:41:49
你可以使用一个特征风格的助手类。
template<typename T> CVectorTraits {};
template<> CVectorTraits<double> { typedef Point3d PointType; }
template<> CVectorTraits<float> { typedef Point3f PointType; }
template<typename T> class CVector3
{
CVector3<T> &normalize();
// more stuff
typename CVectorTraits<T>::PointType toPoint() const;
};发布于 2013-07-12 21:44:36
您可以使用类型特征:
template<typename T>
struct VectorTraits;
template<>
struct VectorTraits<float> {
typedef Point3f Point;
};
template<>
struct VectorTraits<double> {
typedef Point3d Point;
};
template<typename T> class CVector3
{
CVector3<T> &normalize();
typename VectorTraits<T>::Point
toPoint() const;
// more stuff
};
typedef CVector3<float> Vector3f;
typedef CVector3<double> Vector3d;https://stackoverflow.com/questions/17616120
复制相似问题