首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++:扩展模板类

C++:扩展模板类
EN

Stack Overflow用户
提问于 2013-07-12 21:31:33
回答 4查看 6.2K关注 0票数 3

我得到了以下信息:

代码语言:javascript
复制
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替换为:

代码语言:javascript
复制
class Vector3f: public CVector3<float>
{
    Point3f toPoint() const;
};

class Vector3d: public CVector3<double>
{
    Point3d toPoint() const;
};

然而,这不起作用,因为现在normalize()被破坏了:它不再返回一个Vector3f,而是一个与Vector3f不兼容的CVector3,因为它实际上是基类。我可以在基类中添加normalize()和任何其他公共方法的包装器方法,但我不想这样做,因为这会使维护这些类变得单调乏味。

我还尝试将typedefs放回模板定义中,并在模板定义之外添加:

代码语言:javascript
复制
template<>
Point3f CVector3<float>::toPoint() const;

template<>
Point3d CVector3<double>::toPoint() const;

这不会编译,因为toPoint()没有在模板定义中声明。我不能把它放进去,因为返回类型是Point3f/Point3d。

我该怎么做呢?任何帮助都是非常感谢的!

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-07-12 21:56:17

感谢你的回复,我现在已经想出了一个可行的方法:

代码语言:javascript
复制
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():

代码语言:javascript
复制
template<>
Point3f CVector3<float, Point3f>::toPoint() const
{
    Point3f pt = { x, y, z };
    return pt;
}

您对特征的回答当然是一个更通用的解决方案,但是由于Point3f是Vector3f的天然挂件,所以我更喜欢第二个模板参数。

票数 0
EN

Stack Overflow用户

发布于 2013-07-12 21:41:49

你可以使用一个特征风格的助手类。

代码语言:javascript
复制
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;
};
票数 3
EN

Stack Overflow用户

发布于 2013-07-12 21:44:36

您可以使用类型特征:

代码语言:javascript
复制
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;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17616120

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档