简体   繁体   中英

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?

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

You can use an instanciation of std::greater as a default argument:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM