I use data structures, and I sort these data structures a lot. These data structures are holding pointers to objects, not directly the objects themselves. Now I can write a simple comparison functor, or function, to tell the sort algorithm how to sort the pointers:
struct Object_ptr_comparer {
bool operator()(const Object* first, const Object* second) {
return *first < *second;
}
};
And use for example std::sort:
Object_ptr_comparer comp;
std::sort(data_str.begin(), data_str.end(), comp);
The only problem with this solution that I have to write extra pointer comparator functor for any type of class. Yes, I could use inheritance and polymorphism to write only the comparator of some root class, but I don’t want to. Is there any other smart way to do this?
That’s what templates are for!
Since I’ve templated the operator rather than specializing the comparer directly, the compiler can deduce the types, so we don’t have to put the types directly.
I use
std::lessrather thanoperator<, because it safely compares pointers to pointers (likechar**), rather than relying on Undefined Behavior.std::lessfalls back onoperator<, so it doesn’t add any complexity to calling code, and there should be no downside.I’m certain this one compiles