C++函子以防止重复?

Functors in C++ to prevent duplication?

本文关键字:C++      更新时间:2023-10-16

重要提示:我正在根据C++11标准编码

我必须为我的IntMatrix类编写以下运算符(检查矩阵中的每个元素是否都<,>,==,!=,etc...给定参数(:

IntMatrix operator< (int num) const;
IntMatrix operator> (int num) const;
IntMatrix operator>= (int num) const;
IntMatrix operator<= (int num) const;
IntMatrix operator== (int num) const;
IntMatrix operator!= (int num) const;

因此,为了防止代码重复,并且由于实现几乎相同,我想编写一个名为between(int from, int to)的函子来检查数字是否在给定字段中。

例如:

对于operator>我会使用 between(num+1,LargestPossibleint(

对于operator<:之间(SmallestPossibleInt,num-1(

对于介于(数,数(之间的operator==:

对于介于(num+1,num-1(之间的operator!=:

但是正如你所看到的,我的代码依赖于我不想要的LargestPossibleint和SmallestPossibleInt等值,(并且不相信这是一个好的解决方案( 有人可以建议对此进行编辑(也许参数的默认值可能会有所帮助(?

更新:我不能使用 lambda、宏或任何不在标准级别的东西我学到了什么? C++中的所有基本内容,类,函子,操作重载,模板,通用代码...

您可以使用模板并编写以下函数:

template<class Comp>
bool cmp_with(int num, Comp cmp) const {
for(size_t i =0 ; i < width; ++i) {
for(size_t j = 0; j< height; j++) {
if(!cmp(matrix[i][j], num)) { 
return false;
}
}
}
return true;
}

当然,您必须通过元素访问等来适应这一点。 然后像这样使用它:

bool operator<(int num) const {
return cmp_with(num, std::less<int>{});
}

等等。请参阅此处了解您需要的不同函数对象(如std::less(。

没有 lambda?马克罗!

#define ALLOF(op) 
bool operator op (int num) const { 
for (auto& v : data) if (!(v op num)) return false; 
return true; 
}
ALLOF(<)
ALLOF(<=)
ALLOF(>)
ALLOF(>=)
ALLOF(==)
ALLOF(!=)
#undef ALLOF
相关文章:
  • 没有找到相关文章