模板类,必要时使用int、short或float
Template - class that uses int, short or float when necessary
我想写一个管理欧几里得向量的类,并使用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;
}
对于double
和int
类型,它将生成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)
{
}
...
}
请注意,即使您提供了这个模板化的复制构造函数,编译器也会为您生成一个复制构造函数(当T
与U
相同时)。在这种情况下,您可以使用默认实现-它完全可以满足您的需要。否则,您还必须显式地定义非模板化的构造函数(和复制赋值)。
相关文章:
- 'short int'持有的值溢出,但"自动"不会溢出?
- 从“ int”到'int16_t {aka short int}'内部{}的“((int)a) -1)”的缩小转换
- 如果超过 short int(c++) 的最大值会发生什么
- C++ 中有符号 int 和无符号 short 的比较
- Short Int基掩码在C 库子弹中的工作方式
- 为什么C/C++会自动将char/wchar_t/short/bool/enum类型转换为int
- 为什么编译器将"char"与"int"匹配而不是"short"?
- 为什么 foo(short int *) 和 bar(signed short *) 认为 QT 的签名不同
- 错误:从 'short unsigned int*' 到"短无符号 int"的转换无效|(在 C++ 中)
- wchar_t*到short int的转换
- 将无符号short/int强制转换为char*
- 像javashort[]一样在c中创建short int数组
- C/C++:在32位机器上的sizeof(short)、sizeof(int)、sizeof(long)、size of
- 对'icu_56::UnicodeString::UnicodeString(signed char, unsigned short const*, int)' 的未定义引用
- 将无符号字符转换为 int 和 short
- gcc 奇怪的转换警告(<B>从"int"转换为"A::count_type {aka short unsigned int}"可能会改变其值)
- 对类中的整数成员变量使用short、int或long
- 让template通过指定bitsize在char/short/int之间进行选择
- 是实现定义的unsigned short + int类型
- 为什么在C和c++中进行算术运算之前必须将short类型转换为int类型?