## Definition

A function pointer allows a pointer to a function to be passed as a parameter to another function. Functors (Function Objects) in C++ allows the function call operator() to be overloaded. It allows instantiated object of a class to be called like a function.

Advantages of functor compared to function pointer

- Functor fits into OOP paradigm as compared to function pointer.
- Unlike function pointer, functor can have state.
- A functor often may be inlined unlike function pointer.
- Calling the overloaded operator() can be more efficient than dereferencing a function pointer

## Standard Functors

Basic functor concepts in STL:

- Generator : Functor with no arguments
- UnaryFunction: Functor with one argument
- BinaryFunction: Functor with two arguments
- UnaryPredicate: UnaryFunction returning bool
- BinaryPredicate: BinaryFunction returning bool

Standard library defines several adaptable function objects corresponding to common operators. For example,

- Comparison operators (binary predicates)
- equal_to, not_equal_to
- less, greater, less_equal, greater_equal

- Arithmetic operators
- plus, minus, multiplies, divides, modulus (binary functions)
- negate (unary function)

- Logical operators
- logical_not (unary predicate)
- logical_and, logical_or (binary predicates)

Many functions in the library, expects something like a function to be passed. For example signature of `std::for_each`

template< class InputIt, class UnaryFunction > UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );

Type `UnaryFunction`

is expected to be pass by value, and can be called like a function (f(value)). There are a couple things that satisfy this:

- Function pointers
- Functor objects, which are instances of a class that overloads operator()
- Lambdas (which are really just functor objects)

## Example

Functors are objects that can be treated as though they are a function or function pointer. Below example creates a functor class with a constructor that takes an argument. When object of the class is called, it will return the result of adding the saved value and the argument to the functor.

#include <iostream> class FunctorClass { public: FunctorClass(int x) : val(x) { } // Functor double operator() (double y) { return val + y; } private: double val; }; int main() { // Create object FunctorClass obj(5); // Call functor // Output : 94 std::cout << obj(89); return 0; }

In the below example, functor will be invoked for each element of the vector v, and prints out one by one after adding 10.

#include <iostream> #include <vector> #include <algorithm> class FunctorSTL { public: FunctorSTL(int k) : val(k) { } void operator()(int i) { std::cout << i + val << " "; } private: int val; }; int main(){ std::vector<int> v = { 1, 2, 3, 4, 5 }; int val = 10; // Output: 11 12 13 14 15 for_each(v.begin(), v.end(), FunctorSTL(val)); }