1

I am trying to write a template with custom compare function

#include <list>
#include <algorithm>

using std::list;
using std::sort;

template<class T, class Comp=std::less<T>>
class MyList{
    public:
    list<T> l;
    
    void add(const T& t){
        l.push_back(t);
    }
    
    void sort(){
        sort(l.begin(),l.end(), Comp);
    }
};

int main()
{
    MyList<int> myList;
    myList.add(1);
    myList.sort();
    
    return 0;
}

However, I fail to put the compare function as the argument of sort function

main.cpp: In member function ‘void MyList<T, Comp>::sort()’:
main.cpp:26:37: error: expected primary-expression before ‘)’ token
         sort(l.begin(),l.end(), Comp);
David Tong
  • 31
  • 3
  • 1
    `Comp` is a type. `std::sort(...)` needs you to pass an object to it, not a type. That might be `Comp{}` as a default, or you might want to let calling code pass a specific `Comp` instance. – Nathan Pierson Oct 18 '22 at 04:37
  • 1
    Also: you cannot use `std::sort` for `std::list`. See: https://stackoverflow.com/questions/10652674/sorting-stdlists-using-stdsort. – wohlstad Oct 18 '22 at 04:40

0 Answers0