模板比较操作员

Template compare operator

本文关键字:操作员 比较      更新时间:2023-10-16

我有以下模板类:

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;
}

如果LeftTypeRightType Integer都启用integer case,并且启用real case如果至少一个LeftTypeRightType是真实的?

怎么样:

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是一个基本名称,因此显然应该在名称空间中)