Search code examples
c++sortingsetfunctor

Use public function as sorting criteria, C++;


Consider this example, I have public function less that I want to use as a comparator.
P.S. I know if I change it to operator< it will work.

class A {
    std::string str;
    int id;
public:
    virtual bool less(A const& rhs) const{
        return id < rhs.id;
    }
};

int main()
{
    std::set<A, A::less> s;
}

This gives me an error that less is not a valid template.
Can anyone please help me to pass lass as a comparator? If its not possible can you tell me any workaround without touching the class itself.


Solution

  • The second parameter of std::set needs to be a type, not a value.

    It also has to be a type where comp(a, a) is a valid expression, where comp is a value of the compare type, and a is a value of the element type, so we can't use a pointer-to-member-function directly.

    std::set<A, decltype(std::mem_fn(&A::less))> s(std::mem_fn(&A::less)));