A functor, or function object, is a class in C++ with the () operator overloaded. Functors are used a lot in the standard library to do custom comparisons. They're used in place of function pointers because sometimes you need to store a value or remember something (ie. put the functor into a special 'state' for whatever purpose), a functor can do this, a function pointer can't (without messing with global variables).
class over5 { // this class is the functor
bool operator() (int x) {
return x > 5;
}
};
std::list<int> L;
... // put a bunch of ints onto the list
over5 o5;
std::find_if(L.begin(), L.end(), o5);
// o5 will have its overloaded () operator called to check if the element in L is over 5.
4👍 2👎