模板比较操作员
Template compare operator
我有以下模板类:
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;
}
如果LeftType
和RightType
Integer都启用integer case
,并且启用real case
如果至少一个LeftType
或RightType
是真实的?
怎么样:
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是一个基本名称,因此显然应该在名称空间中)
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么比较运算符如此快速
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 比较字符数组
- 将模板化的类型与C++中的某些类/类型进行比较
- C++自定义比较函数
- 如何比较自定义类的std::变体
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- std::设置自定义比较器
- 布尔比较运算符是如何在C++中工作的
- C++将目录中的所有文件与::filesystem进行比较
- >操作员在比较两个C++容器时会怎么做?
- 与操作员比较两个计时时间点
- 比较操作员对字符串的含义是什么?
- 模板比较操作员
- 如何为结构/类字符串实现比较操作员
- 比较操作员的数值精度
- 超载比较操作员
- Stable_sort缺少操作员 - 定义了自定义比较函数
- 比较操作员性能 <= 与 !=