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循環)是相同的,它可能會更好地重載操作符!=真正的類型。 –