我有以下模板类:
template<int size, typename Type>
class Matrix {
public:
Matrix();
...
Type operator ()(int row, int column) {...}
private:
std::array<Type, size*size> _array;
}
我想重载等于
比较运算符来比较Matrix
对象:
template <int size, typename LeftType, typename RightType>
bool operator ==(const Matrix<size, LeftType> & left, const Matrix<size, RightType> & right) {
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
...
}
}
}
问题是整数类型和实数类型的比较是完全不同的:
真实案例
:
template <int size, typename LeftType, typename RightType>
bool operator ==(const Matrix<size, LeftType> & left, const Matrix<size, RightType> & right) {
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
if (qFuzzyIsNull(left(i, j)) || qFuzzyIsNull(right(i, j))) {
if (!qFuzzyCompare(left(i, j) + 1, right(i, j) + 1)) {
return false;
}
} else {
if (!qFuzzyCompare(left(i, j), right(i, j))) {
return false;
}
}
}
}
return true;
}
(我正在使用 Qt 的 qFuzzyCompare 和 qFuzzyIsNull )
整数大小写
:
template <int size, typename LeftType, typename RightType>
bool operator ==(const Matrix<size, LeftType> & left, const Matrix<size, RightType> & right) {
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
if (left(i, j) != right(i, j)) {
return false;
}
}
}
return true;
}
如果 LeftType
和 RightType
都是整数,如何启用整数大小写
,如果至少有一个,如何启用真实大小写
LeftType
或 RightType
是真的吗?
最佳答案
这个怎么样:
template <int size, typename LeftType, typename RightType>
bool operator ==(const Matrix<size, LeftType> & left, const Matrix<size, RightType> & right) {
for (int i = 0; i < size; ++i) {
for (int j = 0; j < size; ++j) {
if (not is_equal(left(i,j), right(i,j)) {
return false;
}
}
}
return true;
}
然后你要么定义 is_equal 的几个重载变体,要么使 is_equal 成为一个模板并定义它的特化,比如
template<class T>
bool is_equal(const T a, const T b);
template<>
bool is_equal<int>(const int a, const int b){
return a == b;
}
template<>
bool is_equal<real>(const real a, const real b){
...
}
(或者如果可能的话,作为两种类型的模板)
当然,您可以专门化运算符本身,但这意味着您必须重新编写相同的代码,没有任何机会重用它。同时,is_equal 可能成为您程序中的一些常用工具。
(注意:is_equal 是一个有点基本的名称,所以它显然应该在命名空间中)
关于c++ - 模板比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42274949/