Search code examples
c++vectoroperatorsclass-template

why define lt when operator< exists?


A piece of code for vector operations contains these class template definitions:

template <class T>
class lt { 
    public: 
    static int compare(T a, T b) { return(a < b); } 
};
template <class T>
class gt { 
    public: 
    static int compare(T a, T b) { return(a > b); } 
};

But why? It's not using extra exception handling, and it relies on objects of class T already having operator< and operator>. Is it not just as easy/easier to use the operators? Or should one use template classes for comparisons?


Solution

  • Those templates can be used whenever someone expects a binary predicate, i.e. a free function taking two parameters. An overloaded operator< may not be defined as a free, binary function, so these templates serve as a sort of adapter to let you use existing operators no matter how they were defined, as long as the expression a < b can be resolved.

    Note that the standard already provides very similar* templates; they're called std::less and std::greater, and they're used for example by the ordered, associative containers.

    *) The standard library predicates provide additional guarantees on how they work on pointers.