function operator()

I saw this function operator() been used here and there. But I can't find much information about it on web. Can anyone please explain what it does, when to use it.

Thanks.


here is a example:
#include <iostream>
#include <algorithm>
using namespace std;

bool myfn(int i, int j) { return i<j; }

struct myclass {
bool operator() (int i,int j) { return i<j; }
} myobj;

int main () {
int myints[] = {3,7,2,5,6,4,9};

// using default comparison:
cout << "The smallest element is " << *min_element(myints,myints+7) << endl;
cout << "The largest element is " << *max_element(myints,myints+7) << endl;

// using function myfn as comp:
cout << "The smallest element is " << *min_element(myints,myints+7,myfn) << endl;
cout << "The largest element is " << *max_element(myints,myints+7,myfn) << endl;

// using object myobj as comp:
cout << "The smallest element is " << *min_element(myints,myints+7,myobj) << endl;
cout << "The largest element is " << *max_element(myints,myints+7,myobj) << endl;

return 0;
}
This is the function call operator.
Read up on function objects (generally called functors for short) for more information.
If you have a type T that overloads operator()(parameters) and an instance of T named a, you can do
 
a(parameters);

The use of this is that a function can be defined like this:
1
2
3
4
template <typename T>
void f(T f2){
    f2(parameters);
}
and the caller can pass either an actual function, or an object of a type that overloads operator() (such as T).
Topic archived. No new replies allowed.