假设我们有以下函数声明
template<typename Function_type , typename Iterator_type>
Iterator_type sort(Iterator_type begin, Iterator_type end, Function_type 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不能用作函数。
在我的第二次尝试中,我宣布了另一个通用函数
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);
尽管如此,我还是没有成功。这样做的正确方法是什么?
答案 0 :(得分:2)
不要指定默认值。只需添加一个重载:
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>{});
}
答案 1 :(得分:1)
您可以使用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())