2017-02-16 2 views
0

비교 I 후속하는 템플릿 클래스가 있습니다템플릿 운영자

template<int size, typename Type> 
class Matrix { 
    public: 
     Matrix(); 
     ... 
     Type operator()(int row, int column) {...} 
    private: 
     std::array<Type, size*size> _array; 
} 

을 그리고 Matrix 개체를 비교 equal to 비교 연산자를 오버로드 할 :됩니다

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 :

적어도 하나의 LeftType 또는 RightType이 진짜 인 경우 LeftTypeRightType 정수 모두가 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 (left(i, j) != right(i, j)) { 
       return false; 
      } 
     } 
    } 
    return true; 
} 

어떻게 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 (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; 
} 

integer case (I는 Qt의 qFuzzyCompareqFuzzyIsNull가 사용하고 있습니다) ?

+4

과부하 ='은'실제 type' 당신이 모두 동일한 기능을 사용할 수 있도록? – NathanOliver

+0

템플릿 전문화를 사용하고 LeftType 및 RightType = int에 대해 하나의 버전을 escpacally 작성할 수 있습니다. 따라서 특수 함수는 둘 다 정수인 경우 항상 호출됩니다. 또한 변환이 필요하지 않은 경우 명시 적으로 추가한다고 생각할 수도 있습니다. – Aeonos

+2

'템플릿 전문화 '가 당신이 찾고있는 것입니다. 하지만 @ NathanOliver 맞아요, (중첩 된 루프) 논리가 동일하며 실제 형식에 대한 연산자! = 오버로드하는 것이 좋습니다. –

답변

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이 다소 기본 이름)!`