我在 C++98 中工作,我想绑定(bind) std::max
。但是我需要一个仿函数对象来与 std::bind1st
一起使用。
我试过只使用 std::pointer_to_binary_function
但问题似乎是我无法用 std::max
制作仿函数:https://stackoverflow.com/a/12350574/2642059
我也试过 std::ptr_fun
但我得到了类似的错误。
最佳答案
由于 this answer 中的问题,你不能为 max 写一个真正的包装仿函数,因为你不能制作任何类型 const T&
。你能做的最好的事情是:
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
但这很糟糕,因为您现在必须 复制所有内容(尽管如果您只是使用 int
,这完全没问题)。最好的办法可能是完全避免 bind1st
:
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;
};
关于c++ - 如何创建最大仿函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27108047/