重要提示:我是按照C++11标准编码的
我必须为我的IntMatrix
类编写以下运算符(它检查矩阵中的每个元素是否都是<,>,==,!=等…
给定的参数):
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)
的函子,它检查数字是否在给定字段中。
例如:
对于运算符>
,我将使用between(num+1,LargestPossibleint)
对于运算符<:
between(SmallestPossibleInt,num-1)
对于operator==:
between(num,num)
对于运算符!=:
之间(num+1,num-1)
但是,正如您所看到的,我的代码依赖于像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