模板 - 在必要时使用int,short或float的类

Cly*_*men 5 c++

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

    template<class unit> class EVector
{
private:
    unit x;
    unit y;
public:
    EVector();
    setX();
    setY();
};
Run Code Online (Sandbox Code Playgroud)

因此,用户创建一个EVector,选择合适的基元类型.但是我如何在不同的类之间实现操作,例如

EVector<int> a;
EVector<float> b;

EVector<double> c;

c = a + b;  
Run Code Online (Sandbox Code Playgroud)

operator =将复制坐标,operator +添加它们.

Joh*_*itb 3

另外,您可以使用我的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;
}
Run Code Online (Sandbox Code Playgroud)

对于类型doubleint,它将产生double例如。