减少班级中的模板混乱

时间:2020-03-22 05:02:11

标签: c++

我确定已经问过了,但是找不到。假设我们有一个简单的模板struct / class,

 template <class T>
 struct Point { 
     T x, y;        
 };  

和另一个使用此对象的结构/类

typedef Point<double> point;          // Is this reasonable??
class UsesPointButOnlyOnFixedType {
    template <class T> 
    void UsePoint1(const Point<T>& p); // Annoying if this class is agnostic to the type
    void UsePoint2(const point& p); // Deceiving 
};

除了UsesPointButOnlyOnFixedType类只能用于单个Point类型(例如double)。因此,在Point类中要求使用UsesPointButOnlyOnFixedType结构的类型定义是毫无意义的。有这种情况的标准做法吗?例如,如上例所示,使用typedef有什么问题吗?

1 个答案:

答案 0 :(得分:1)

如果您在评论中说UsesPointButOnlyOnFixedType仅适用于Point<double>,那么您应该使用

template <class T> 
void UsePoint1(const Point<T>& p);

因为这将允许使用任何类型的Point<...>自变量调用该函数。

您应该使用

void UsePoint1(const Point<double>& p);

您当然可以通过typedef来避免重复模板参数,但是在这种情况下,我会将类型别名放在类中,因为实际上并不需要在其外部显示它:

class UsesPointButOnlyOnFixedType {
    using PointT = Point<double>;

    void UsePoint1(const PointT& p);
    void UsePoint2(const PointT& p); 
};
相关问题