将指向函数的指针类型的函数参数设置为默认值

Setting a function parameter, which is of type pointer to a function to default value

假设我们有以下函数声明

 template<typename Function_type , typename Iterator_type>
   Iterator_type sort(Iterator_type begin, Iterator_type end, Function_type f);

这个函数应该模仿 algorithm 库中包含的许多排序函数之一,因此有一个可选的第三个参数。我需要在此声明中为 f 分配什么值才能避免最后一个参数合法。我最初的想法是使用 lambda 函数

 template<typename Function_type , typename Iterator_type>
  Iterator_type sort(Iterator_type begin, Iterator_type end, Function_type f=[](decltype(*begin)x, decltype(*begin)y){return x>y;});

编译器告诉我 f 不能用作函数。

在第二次尝试中,我声明了另一个泛型函数

 template< typename Type>
  bool Comparison(Type x, Type y)
    {
    return y>x;
    }
 template<typename Function_type , typename Iterator_type>
  Iterator_type sort(Iterator_type begin, Iterator_type end, Function_type f=Comparison);

还是没有成功。执行此操作的正确方法是什么?

不要分配默认值。只需添加一个重载:

template <typename Iter>
Iter Max_el(Iter begin, Iter end) {
    using T = std::remove_reference_t<decltype(*begin)>;
    return Max_el(begin, end, std::greater<T>{});
}

您可以使用 std::greater 的实例作为默认参数:

template<typename Iterator_type, typename Function_type = std::greater<void>>
Iterator_type sort(Iterator_type begin, Iterator_type end, Function_type f = Function_type())

Live demo