kino92
kino92

Reputation: 39

Using default predicate for sort with templates. C++

I'm trying to define the class template as shown below

template <typename T> class test{
       std::list<T> container;
       public:
       template <typename type, typename PRED = std::greater<int>>
        void push(type e, PRED comp = std::greater<int>) {
            container.push_back(e);
            container.sort(comp);
        }

};

From main I want to be able to tell sort how the sorting should be done. But I also want sort to use std::greater if nothing is specified. The code above is telling me that std::greater is illegal.

Upvotes: 1

Views: 239

Answers (1)

Brian Bi
Brian Bi

Reputation: 119219

You probably want to do this:

template <typename type, typename PRED = std::greater<T>>
void push(type e, PRED comp = PRED()) {
    // ...
}

Use std::greater<T> as the default template argument, so that it will work even when T is not int.

Use PRED() as the default value for the comp argument, so that it will work even if the user specifies some other default-constructible predicate type, like std::less<T>.

Upvotes: 2

Related Questions