Search code examples
c++templatesdefault

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


Suppose we have the following function declaration

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

This function is supposed to mimic one of the many sort functions contained in the algorithm library, therefore having a third parameter which is optional. What value do i need to assign to f in this declaration to make avoiding the last parameter legal. My initial thought was to use a lambda function

 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;});

This yielded a result in which the compiler informed me that f cannot be used as a function.

In my second attempt I declared another generic function

 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);

Still, I didn't succeed. What is the proper way to do this?


Solution

  • Don't assign a default value. Just add an overload:

    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>{});
    }