0
我有下面的模板类:模板比较运营商
template<int size, typename Type>
class Matrix {
public:
Matrix();
...
Type operator()(int row, int column) {...}
private:
std::array<Type, size*size> _array;
}
我想重载equal to
比较符来比较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) {
...
}
}
}
的问题是,整数类型和现实的比较类型相当不同:
real case
:
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)
integer case
:
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;
}
如何启用integer case
如果两个LeftType
和RightType
整数,使real case
如果至少一个LeftType
或RightType
是真实的?
超载'='为'真正type'所以你可以使用两个相同的功能!? – NathanOliver
您可以使用模板特化并针对LeftType和RightType = int编写一个版本。因此,如果两者都是整数,那么总是会调用这个特殊函数。也可以考虑在这种情况下添加明确的内容,如果转换不希望。 – Aeonos
'模板专业化'是你在找什么。但@NathanOliver是正确的,逻辑(嵌套for循环)是相同的,它可能会更好地重载操作符!=真正的类型。 –