Mircea Ispas
Mircea Ispas

Reputation: 20780

Easy way to make std::compare functions unary

I need to use different compare functions as unary functions, where one of the values is embedded inside the comparator. To do so I created an adaptor class, something like:

template<typename T, typename Compare>
class CompareAdaptor : private Compare
{
    public:
        CompareAdaptor(T value)
            : mValue(value)
        {
        }

        bool operator()(T v) const
        {
            return Compare::operator()(v, mValue);
        }

    private:
        T           mValue;
};

and now I can define a new unary comparator like:

template<typename T>
using EqualTo = CompareAdaptor<T, std::equal_to<T>>;
template<typename T>
using LessEqual = CompareAdaptor<T, std::less_equal<T>>;

My questions is: Is there a simpler way(without using the adaptor class) to define those unary comparators? I think this is a very common problem and probably you have better solutions.

Upvotes: 0

Views: 609

Answers (2)

m.s.
m.s.

Reputation: 16334

@Quentins answer can also be made compilable in C++11 using std::function as the return type which the lambdas are convertible to:

template <class Comp>
std::function<typename Comp::result_type (typename Comp::first_argument_type)> predicate(typename Comp::second_argument_type rhs)
{
    return [rhs](typename Comp::first_argument_type lhs){
        Comp c{};
        return c(lhs, rhs);
    };
}

live on coliru

Upvotes: 1

Quentin
Quentin

Reputation: 63124

In C++11, this is as good as it gets. But I'd rather expect the predicate to be directly constructed at the call site :

std::find_if(begin(v), end(v), [limit](int i) { return i < limit; });

In C++14, you could use return type deduction to make a factory fuction :

template <class Comp>
auto predicate(typename Comp::second_argument_type rhs) {
    return [c = Comp{}, rhs](typename Comp::first_argument_type lhs) {
        return c(lhs, rhs);
    };
}

Example call : predicate<std::less<int>>(4) returns the function object.

Live on Coliru

Upvotes: 2

Related Questions