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

C++ 将指向函数的指针类型的函数参数设置为默认值,c++,templates,default,C++,Templates,Default,假设我们有下面的函数声明 template<typename Function_type , typename Iterator_type> Iterator_type sort(Iterator_type begin, Iterator_type end, Function_type f); 模板 迭代器类型排序(迭代器类型开始、迭代器类型结束、函数类型f); 该函数应模拟算法库中包含的众多排序函数之一,因此具有第三个可选参数。在这个声明中,我需要为f指定什么值才能使避

假设我们有下面的函数声明

 template<typename Function_type , typename Iterator_type>
   Iterator_type sort(Iterator_type begin, Iterator_type end, Function_type f);
模板
迭代器类型排序(迭代器类型开始、迭代器类型结束、函数类型f);
该函数应模拟算法库中包含的众多排序函数之一,因此具有第三个可选参数。在这个声明中,我需要为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=[](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);
模板
布尔比较(x型、y型)
{
返回y>x;
}
模板
迭代器类型排序(迭代器类型开始,迭代器类型结束,函数类型f=比较);
尽管如此,我还是没有成功。正确的方法是什么?

不要指定默认值。只需添加一个重载:

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>{});
}
模板
国际热核聚变实验堆(国际热核聚变实验堆开始,国际热核聚变实验堆结束){
使用T=std::删除\u引用\u T;
返回Max_el(开始、结束、标准::大于{});
}

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

template<typename Iterator_type, typename Function_type = std::greater<void>>
Iterator_type sort(Iterator_type begin, Iterator_type end, Function_type f = Function_type())
模板
迭代器类型排序(迭代器类型开始,迭代器类型结束,函数类型f=函数类型()

我明白了,但是有没有更通用的方法,我们可以使用任意函数?@Shema为什么你认为这不够通用?所以你的意思是我们应该始终使用封装在类中的通用函数(这就是我对这些东西的描述)?这不是在VS2015下为我编译的。它说它不能推断函数的类型。@u-type。@u-type尝试用两个参数调用它。