簡體   English   中英

C++ 中的仿函數以防止重復?

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

重要提示:我按照 C++11 標准編碼

我必須為我的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;

因此,為了防止代碼重復並且由於實現幾乎相同,我考慮編寫一個名為between(int from, int to)函子,它檢查數字是否在給定字段中。

例如:

對於operator>我會使用 between(num+1,LargestPossibleint)

對於operator<: between(SmallestPossibleInt,num-1)

對於operator==:介於(num,num)之間

對於operator:=: between(num+1,num-1)

但是正如您所看到的,我的代碼取決於我不想要的 LargestPossibleint 和 SmallestPossibleInt 之類的值,(並且不相信這是一個好的解決方案)可能有人建議對此進行編輯(也許參數的默認值可能會有所幫助)?

更新:我不能使用 lambda、宏或任何非標准級別的東西我學到了什么? C++ 中的所有基本內容、類、函子、操作重載、模板、通用代碼......

您可以使用模板並編寫以下 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;
}

當然,您必須通過元素訪問等來調整它。然后像這樣使用它:

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

等等。 有關您需要的不同 function 對象(如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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM