jeudi 11 janvier 2018

Correct approach or design pattern to simplify the `operatorX` functions in a class to compare attributes of the same type in a given order?

In the past I reduced the repetition in operator<, <=, > and >= functions of data type classes by writing a helper function which takes a comparison function as argument.

Simplified, a such class looks like this:

class Foo {
public:
    bool comparison(const Foo &other, std::function<bool(int a, int b)> compFn) {
        if (_a == other._a) {
            if (_b == other._b) {
                 return compFn(_c, other._c);
            }
            return compFn(_b, other._b);
        }
        return compFn(_a, other._a);
    }
    bool operator<(const Foo &other) const {
        return comparison(other, &std::less<int>::operator())
    }
    bool operator<=(const Foo &other) const {
        return comparison(other, &std::less_equal<int>::operator())
    }
    bool operator>(const Foo &other) const {
        return comparison(other, &std::greater<int>::operator())
    }
    bool operator>=(const Foo &other) const {
        return comparison(other, &std::greater_equal<int>::operator())
    }
private:
    int _a;
    int _b;
    int _c;
};

The real classes use complexes data types, but the principle stays the same. The comparison less or greater is a comparison of a number of attributes in a given order.

Using the comparison function I can change this order at any time, just rewriting a single function. Also the logic is at a single point and not repeated in four places.

Is there a established design pattern to cover this situation?

I realised that there are already the comparison objects, like std::less. But I could not find a simple way to use them instead instead of the shown solution.

Can the shown solution further simplified using other language features or the standard library?

Aucun commentaire:

Enregistrer un commentaire