what are functors in c++ and its uses explain with example?

functors are called function objects. Basically functors are classes or structs which overide operator ().  Overloading operator() enables us to create objects which “look like” a function. Let us see below example. The class add which is overloading operator().

In the above example object of class add behaves like a function.

  • A simple use case of using functor in templates.

Let us assume we have a vector<int> vec = { 1,3,5,8,7,9}. now we need to count how many integers in  vec are greater than 5 using count_if algorithm.

Let us see below example using functor in count_if in c++

what are advantages of using functors in c++

  • Functors may have state while function does not.
  • Most of the compilers often transform functors as inlined.
  • Functors can be used to implement callbacks.

Ref:

https://en.wikipedia.org/wiki/Function_object




Related Contents to follow