Paul Baltescu
Paul Baltescu

Reputation: 2255

What is the difference between operator() and operator< in C++?

Whenever I have C++ entities that I want to compare I just implement operator<. However, reading other people's code I saw that the same can be achieved by implementing operator().

What is the difference between the two? When should each of these operators be used?

Upvotes: 2

Views: 257

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385088

operator< is the canonical way to define a comparison operator:

struct A { /* some members */ };
struct B { /* some members */ };

// comparison operator
bool operator<(const A&, const B&);

This gives you the conventional usage:

int main()
{
   A a;
   B b;

   const bool result = (a < b);
}

What you've seen is people creating functors; that is, entire classes whose sole purpose is to wrap a comparison. To make these look a bit like functions to calling code, they use operator():

struct A { /* some members */ };
struct B { /* some members */ };

// comparison functor
struct comparator
{
   bool operator()(const A&, const B&);
};

This gives you a less conventional usage in code equivalent to my previous example:

int main()
{
   A a;
   B b;

   comparator c;
   const bool result = c(a,b);
}

However, you wouldn't use it for this. Functors are for passing to algorithms (particularly in generic code). They also have the added benefit of being able to hold state, since you have constructor arguments to play with. This makes them more flexible than a simple function pointer.

int main()
{
   std::vector<A> a(5);
   B b;

   comparator c;
   std::sort(a.begin(), a.end(), c);

   // or, simply:
   std::sort(a.begin(), a.end(), comparator());

   // all more easily extensible than:
   std::sort(a.begin(), a.end(), &someComparisonFunction);
}

Upvotes: 5

Related Questions