简体   繁体   English

C++ 中的仿函数以防止重复?

[英]Functors in C++ to prevent duplication?

Important Note: I am coding according to C++11 standard重要提示:我按照 C++11 标准编码

I have to write the following operators for my IntMatrix class (which check if every element in the matrix is <,>,==,,=.etc... the given parameter):我必须为我的IntMatrix class 编写以下运算符(检查矩阵中的每个元素是否为<,>,==,,=.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;

So, to prevent code duplications and since the implementation is nearly the same I thought about writing one functor called between(int from, int to) which checks if number is in a given field.因此,为了防止代码重复并且由于实现几乎相同,我考虑编写一个名为between(int from, int to)函子,它检查数字是否在给定字段中。

For example:例如:

for operator> I would use between(num+1,LargestPossibleint)对于operator>我会使用 between(num+1,LargestPossibleint)

for operator<: between(SmallestPossibleInt,num-1)对于operator<: between(SmallestPossibleInt,num-1)

for operator==: between(num,num)对于operator==:介于(num,num)之间

for operator:=: between(num+1,num-1)对于operator:=: between(num+1,num-1)

But as you can see my code depends of values like LargestPossibleint and SmallestPossibleInt which I don't want, (And don't believe this is a good solution) May someone suggest an edit for this (Maybe default value for parameters may help)?但是正如您所看到的,我的代码取决于我不想要的 LargestPossibleint 和 SmallestPossibleInt 之类的值,(并且不相信这是一个好的解决方案)可能有人建议对此进行编辑(也许参数的默认值可能会有所帮助)?

Update: I can't use lambda, macros or anything not in standard level What I learnt?更新:我不能使用 lambda、宏或任何非标准级别的东西我学到了什么? All basic stuff in C++, classes, functors, operation overloading, templates, generic code... C++ 中的所有基本内容、类、函子、操作重载、模板、通用代码......

You could use templates and write the following function:您可以使用模板并编写以下 function:

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

Of course, you have to adapt this with your element access etc. Then use it like this:当然,您必须通过元素访问等来调整它。然后像这样使用它:

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

and so on.等等。 See here for the different function objects (like std::less ) you need.有关您需要的不同 function 对象(如std::less ),请参见此处

No lambda?没有 lambda? Macrology!赘言!

#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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM