Function objects (functors) in C++

Following code explains how a function object (or Functor) can be defined and used.

#include <iostream>
using namespace std;

class cls_functor {
    public:
    void operator()() {
        cout << "Function object called " << endl;
    }
   
    // accepting int value as parameter
    void operator()(int val) {
        cout << "Function object called with value: " << val << endl;
    }
   
    // passing function object as parameter
    void operator()(cls_functor& ptr) {
        cout << "Function object with a function object as parameter: " << endl;
       
        ptr();
    }
};


void fun_call_by_reference(cls_functor& ptr){
    ptr();
   
    ptr(100);
   
    ptr(ptr);
}


void fun_call_by_pointer(cls_functor* ptr){
    (*ptr)();
   
    (*ptr)(200);
   
    (*ptr)(*ptr);
}


int main()
{
    cls_functor ptr;
   
    fun_call_by_reference(ptr);
   
    cls_functor* ptr1 = new cls_functor();
   
    fun_call_by_pointer(ptr1);

    return 0;
}


/********** OUTPUT **********
Function object called
Function object called with value: 100
Function object with a function object as parameter:
Function object called
Function object called
Function object called with value: 200
Function object with a function object as parameter:
Function object called

*/

Functor Vs Function pointers

Functors (or Function objects) are better because
* Functors can maintain state like any other instance created from a custom class.
* They have simpler syntax and extendable

No comments:

Post a Comment