我想编写一个类来管理欧几里德 vector 并使用短整型、整型、长整型或浮点型存储其初始点。我想创建一个这样的模板:
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;
}
例如,对于类型 double
和 int
,它将产生 double
。
关于c++ - 模板 - 必要时使用 int、short 或 float 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6722568/