How do I create the maximum functor?
I am working in C ++ 98 and I want to bind std::max
. But I need a functor object to use with std::bind1st
.
I tried to use std::pointer_to_binary_function
, but the problem is that I can't make a functor from std::max
: stack overflow question.
I also tried std::ptr_fun
it but I get a similar error.
source to share
Due to the problem in this answer, you cannot write a true wrapper functor for max, because you cannot do 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 now you have to copy everything (although if you just use int
s, that's perfectly fine). Your best bet would be to just avoid it 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;
};
source to share