0

I came across this code with operator(). I have never seen this before (I have seen +,>,- <<). Can someone explain when it should be used and how it should be used?

 class sortResults
    {
    public:
        bool operator() (Result const & a, Result const & b);
    };
vkaul11
  • 4,098
  • 12
  • 47
  • 79

2 Answers2

5

This is called a functor (not to be confused with a functor in functionnal programming languages).

It mimics a function and can be used as such in functions from the standard library :

std::vector<Result> collection;
// fill with data

// Sort according to the () operator result
sortResults sort;
std::sort(collection.begin(), collection.end(), sort);

A nice advantage compared to simple functions, is that it can hold a state, variable, etc. You can make a parallel with closures (if that rings a bell)

struct GreaterThan{
    int count;
    int value;
    GreaterThan(int val) : value(val), count(0) {}
    void operator()(int val) {
        if(val > value)
            count++;
    }
}

std::vector<int> values;
// fill fill fill

GreaterThan gt(4);
std::for_each(values.begin(), values.end(), gt);
// gt.count now holds how many values in the values vector are greater than 4
Tristram Gräbener
  • 9,601
  • 3
  • 34
  • 50
  • 3
    The snippet is kind of confusing as your initializing `sortResults` with brackets too. Better define it before the `std::sort` call to make the point clear. – Sebastian Hoffmann Aug 06 '13 at 16:43
1

It means that a sortResults instance can be called, just like a function taking two Result parameters:

sortResults sr;
Result r1, r2;
bool b = sr(r1, r2);

Such a class is referred to as a "functor". Most standard library algorithms have overloads that take unary or binary functors such as this one.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480