简体   繁体   中英

Functors in C++ to prevent duplication?

Important Note: I am coding according to C++11 standard

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 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.

For example:

for operator> I would use between(num+1,LargestPossibleint)

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

for operator==: between(num,num)

for 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)?

Update: I can't use lambda, macros or anything not in standard level What I learnt? All basic stuff in C++, classes, functors, operation overloading, templates, generic code...

You could use templates and write the following 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.

No 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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