c++ - 模板比较运算符

标签 c++ templates

我有以下模板类:

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

我想重载等于比较运算符来比较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) {
            ...
        }
    }
}

问题是整数类型和实数类型的比较是完全不同的:

真实案例:

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 )

整数大小写:

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 都是整数,如何启用整数大小写,如果至少有一个,如何启用真实大小写 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 是一个有点基本的名称,所以它显然应该在命名空间中)

关于c++ - 模板比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42274949/

相关文章:

c++ - 为什么 auto 不适用于某些 lambda

c++ - Qt 计算器中更少的连接

c++ - C : Using substr to parse a text file

c++ - 声明采用模板参数的函数

c++ - dynamic_pointer_cast 的模板参数

c++ - 使用 libxml2 从 C++ 中的 XML <tag> 获取值

c++ - 安全地以模块化方式乘以无符号整数的最佳 C++ 方法是什么?

c++ - 什么时候我们需要显式实例化模板函数?

c++ - 迭代器和模板

c++ - std::is_assignable 和 const 指针对象