How Do I Create a max Functor?

1.2k views Asked by At

I'm working in C++98 and I want to bind std::max. But I need a functor object to use with std::bind1st.

I've tried just using std::pointer_to_binary_function but the problem seems to be that I can't make a functor out of std::max: https://stackoverflow.com/a/12350574/2642059

I've also tried std::ptr_fun but I get a similar error.

1

There are 1 answers

1
Barry On BEST ANSWER

Because of the issue in this answer, you can't write a true wrapper functor for max because you can't make any of the types const T&. The best you can do is:

template <typename T>
struct Max
: std::binary_function<T, T, T>
{
    T operator()(T a, T b) const
    {
        return std::max(a, b);
    }
};

std::bind1st(Max<int>(), 1)(2) // will be 2

But that sucks, since you now have to copy everything (although if you're just using ints, this is totally fine). Best would probably be to just avoid bind1st altogether:

template <typename T>
struct Max1st
{
    Max1st(const T& v) : first(v) { }

    const T& operator()(const T& second) const {
        return std::max(first, second);
    }

    const T& first;
};