4

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.

Community
  • 1
  • 1
Jonathan Mee
  • 37,899
  • 23
  • 129
  • 288
  • 1
    `std::max` on what types? In C++98, I don't think `std::bind1st` works on compile time polymorphic function objects, which is the only way to fully wrap all `std::max` overloads into a single function object. – Yakk - Adam Nevraumont Nov 24 '14 at 15:24
  • If this to find the max element in an array? Maybe you can use `std::max_element` – Neil Kirk Nov 24 '14 at 15:28
  • @Yakk I specifically need it for `int`s, though I'd like to know how to do it in the future for other types. I thought that by doing `std::max` the compiler would create the function and it would behave like a regular function pointer? – Jonathan Mee Nov 24 '14 at 15:31
  • @NeilKirk I primarily wanted to use it in `std::accumulate` and `std::transform`. – Jonathan Mee Nov 24 '14 at 15:34
  • 1
    If you have only C++98, trying to use fancy functional programming is just an exercise in getting a migraine, I'm afraid. – Neil Kirk Nov 24 '14 at 15:39
  • @PiotrS. I have looked at that, but I have trouble justifying it just for this instead of writing my own `std::max` functor. – Jonathan Mee Nov 24 '14 at 16:48

1 Answers1

2

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;
};
Community
  • 1
  • 1
Barry
  • 286,269
  • 29
  • 621
  • 977
  • The longer I worked on this the more I had that sinking feeling that this was the only way to accomplish it. I'm going to keep question open another day or so to see if anyone has a better solution then I'll accept this. – Jonathan Mee Nov 24 '14 at 15:38