模板类,必要时使用int、short或float

Template - class that uses int, short or float when necessary

本文关键字:int short float      更新时间:2023-10-16

我想写一个管理欧几里得向量的类,并使用short, int, long或float存储其初始点。我想创建一个这样的模板:

    template<class unit> class EVector
{
private:
    unit x;
    unit y;
public:
    EVector();
    setX();
    setY();
};

所以用户创建了一个选择合适原语类型的EVector。但是如何实现不同类之间的操作呢?例如

EVector<int> a;
EVector<float> b;
EVector<double> c;
c = a + b;  

operator=将复制坐标,operator+将它们相加。

另外,您可以使用我的promote实现:

template<typename A, typename B> 
EVector<typename promote<A, B>::type>
operator +(EVector<A> const& a, EVector<B> const& b) {
  EVector<typename promote<A, B>::type> ev;
  ev.setX(a.getX() + b.getX());
  ev.setY(a.getY() + b.getY());
  return ev;
}

对于doubleint类型,它将生成double

U可转换为T时,您希望启用从EVector<U>EVector<T>的分配(和复制构造)

template<class T>
class EVector
{
   template<class U>
   EVector(EVector<U> const & rhs)
           :x(rhs.x), y(rhs.y)
   {
   }
   ...
}

请注意,即使您提供了这个模板化的复制构造函数,编译器也会为您生成一个复制构造函数(当TU相同时)。在这种情况下,您可以使用默认实现-它完全可以满足您的需要。否则,您还必须显式地定义非模板化的构造函数(和复制赋值)。