2017-02-16 111 views
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的qFuzzyCompareqFuzzyIsNull

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如果兩個LeftTypeRightType整數,使real case如果至少一個LeftTypeRightType是真實的?

+4

超載'='爲'真正type'所以你可以使用兩個相同的功能!? – NathanOliver

+0

您可以使用模板特化並針對LeftType和RightType = int編寫一個版本。因此,如果兩者都是整數,那麼總是會調用這個特殊函數。也可以考慮在這種情況下添加明確的內容,如果轉換不希望。 – Aeonos

+2

'模板專業化'是你在找什麼。但@NathanOliver是正確的,邏輯(嵌套for循環)是相同的,它可能會更好地重載操作符!=真正的類型。 –

回答

1

如何:

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是一個有些基本的名字,所以它應該是在一個命名空間,很明顯)