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

Posted

技术标签:

【中文标题】C ++中的仿函数以防止重复?【英文标题】:Functors in C++ to prevent duplication? 【发布时间】:2020-06-06 12:52:23 【问题描述】:

重要提示:我是按照 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&gt;,我会使用 between(num+1,LargestPossibleint)

对于operator&lt;: between(SmallestPossibleInt,num-1)

对于operator==: between(num,num)

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

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

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

【问题讨论】:

这能回答你的问题吗? What are the basic rules and idioms for operator overloading? 顺便说一句,这是一个常见的抱怨。以至于他们标准化了一个新的运算符 来减少所有的样板。很快我们就会有可以提供帮助的元类 如果使用 C++20,请查找“宇宙飞船运算符”作为起点。 @dfri 不,我的问题完全不同 @Peter 我正在使用 C++11 【参考方案1】:

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

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

等等。请参阅 here 了解您需要的不同功能对象(如 std::less)。

【讨论】:

我不能用这个 @clark_smith 您不允许使用哪些具体内容? 更新不排除我回答中使用的任何内容。 @Ikaros - 这个问题的限制表明这是一个家庭作业。在家庭作业练习中,不使用除 I/O 之外的标准库中的任何东西,不使用宏(尽管我不会在 C++ 中使用它们)来实现事物是相当普遍的,.....【参考方案2】:

没有 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

【讨论】:

对不起!忘了提我的教授认为定义和宏总是不好的解决方案...... @clark_smith:大多数时候他们确实很糟糕......但总是质疑在 IT 中使用“永远”这个词的人 ;-) @6502 这太可怕了。我喜欢它;-)

以上是关于C ++中的仿函数以防止重复?的主要内容,如果未能解决你的问题,请参考以下文章

C/C++中的指针

C中的计时函数[重复]

将函数应用于两列并将输出映射到新列[重复]

如何防止 jQuery 函数中的重复?

POD 的 C++11 中的构造函数要求 [重复]

是否可以防止 C 共享库中的函数覆盖?