dlavila
dlavila

Reputation: 1212

Implementing a custom comparator with a functor template

I want to write custom comparators for functions like lower_bound, find, etc. Below is an example of a custom comparator implemented with a functor that takes another function object (std::less, std::greater, etc) and use it to compare the first element of a pair with the second argument of the function.

template <template <typename> class P = std::less>
struct custom_comp {
    template <class T1, class T2>
    bool operator()(const std::pair<T1, T2>& pair, const T1& val)
    {
            return P<T1>()(pair.first, val);
    }
}

Usage example:

vector<pair<int,int>> vec = {{1, 4}, {3, 3}, {5, 6}, {8, 8}};
auto first = lower_bound(begin(vec), end(vec), 5, custom_comp<>());

However the <>() bothers me, I feel it takes away readability. Is there a way to get rid of it? (perhaps changing the functor for another kind of structure).

btw: I don't want to use lambdas because I want to reuse these custom comparators and even extend them to take more template arguments (like custom filters, e.g a functor that takes a pair and returns pair.first, or a functor that takes the mean of a vector, etc).

Upvotes: 2

Views: 637

Answers (1)

Barry
Barry

Reputation: 302842

However the <>() bothers me

It shouldn't. Nothing wrong with that code. Sometimes you need to do that sort of thing. It doesn't really take away from readability, it's pretty clear what's going on there.

If you want, you could always just create the "default" custom_comp:

constexpr custom_comp<> def_custom_comp{};

And then use it:

auto first = lower_bound(begin(vec), end(vec), 5, def_custom_comp);

You lose the <>(), but I'm not sure that's necessarily easier to understand.

Upvotes: 6

Related Questions