c++ - 如何创建最大仿函数?

标签 c++ max bind functor c++98

我在 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/

相关文章:

ios - 不同iOS版本中Int的最大值是多少?

r - R 数据框中的十个最高列值

algorithm - 表格的多变量最大化

c++ - 实现 Bind()(LINQ 中的 SelectMany)而不产生 yield (在 C++ 中)

java - Spring MVC 使用 GET 请求提交并绑定(bind)对象

c++ - std::bind2nd 和 std::bind 与二维数组和结构数组

c++函数语法/原型(prototype) - 括号后的数据类型

C++ 避免输入构造函数

c++ - 如何确定知名组中用户的成员身份为 Everyone

javascript - 如何在 QML 中延迟 JavaScript Action ?