I’m writing a linked list for a C++ class and am stuck trying to figure out how to compare two generic typed nodes for a sorting algorithm. In Java I would just implement the Comparable interface and use the compareTo() method to determine which is “larger” or “smaller”, letting the user of the Collection define this. Is there something similar in C++ that I can use? I know I can override the “<” operator but I don’t know if this is the “best” method (subjective, I know; really just asking for pros and cons if there is another) to compare unknown types.
So, are there any other options to compare unknown types at runtime that seem to be more appropriate than overriding the “<” operator?
EDIT: Changed the operator I need to override.
From what I gather you have a list class template and you want to implement a
sort()method on it. I would follow the example set bystd::list<T>for this:That is, instead of making a fixed choice you would default to use
operator<()but allow the user to use a different ordering predicate. As long as the comparison function implement a strict weak order anything can be used.