alle_meije
alle_meije

Reputation: 2480

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?

Upvotes: 0

Views: 248

Answers (2)

fer y
fer y

Reputation: 525

The Thing is that comparison is not always numerical.Sometimes two objects can be compared and greater than or less Than can have new definitions .For example in a class that holds objects of type Coordinates Comparison can be defined in a custom way. For example :

Coordinate c1(3,5)
Coordinate c2(4,2)

We can overload the > operator to return True for c1>c2 whenever c1.x > c2.x or c1.y>c2.y

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477110

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.

Upvotes: 4

Related Questions