【问题标题】:How Do I Create a max Functor?如何创建最大仿函数?
【发布时间】:2014-11-24 15:14:07
【问题描述】:

我正在使用 C++98,我想绑定 std::max。但我需要一个函子对象来与std::bind1st 一起使用。

我试过只使用std::pointer_to_binary_function,但问题似乎是我无法用std::max制作仿函数:https://stackoverflow.com/a/12350574/2642059

我也尝试过std::ptr_fun,但我得到了类似的错误。

【问题讨论】:

  • std::max 关于什么类型?在 C++98 中,我认为 std::bind1st 不适用于编译时多态函数对象,这是将所有 std::max 重载完全包装到单个函数对象中的唯一方法。
  • 如果这样可以找到数组中的最大元素?也许你可以使用std::max_element
  • @Yakk 我特别需要它用于ints,但我想知道将来如何为其他类型执行此操作。我认为通过 std::max<int> 编译器会创建函数并且它的行为就像一个常规函数指针?
  • @NeilKirk 我主要想在std::accumulatestd::transform 中使用它。
  • 如果你只有 C++98,尝试使用花哨的函数式编程恐怕只是一种偏头痛的练习。

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


【解决方案1】:

由于 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

但这很糟糕,因为您现在 必须 复制所有内容(尽管如果您只是使用 ints,这完全可以)。最好的办法可能是完全避免 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;
};

【讨论】:

  • 我在这方面工作的时间越长,我就越有一种下沉的感觉,那就是这是完成它的唯一方法。我将在另一天左右保持问题开放,看看是否有人有更好的解决方案,然后我会接受这个。
猜你喜欢
  • 2012-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多