Function object
It is also called as “functor”. It is used to define an object that can be called as function. In other word “object()” is used to call function and function is defined as operator()(){}. We need to write the function logic in operator()(){} and need to call this function using “object()”. Example:
bool operator()(int val) const { //function logic } // creating object className object; //Calling function object bool result = object();
When will we use it (What is the Objective/purpose of functor):
- When we want to pass the function logic as argument to algorithm.
Advantage:
- No need to think about function Name, just use unnamed functor.
- functor will be inline function.
source code with example:
/* Program: Function object (functor) Author: Alpha Master Date: 22 Feb 2021 */ //Header File #include<iostream> #include<vector> class IntCompare { int m_iX; public: IntCompare(int val):m_iX(val){} bool operator()(int val) const { //std::cout<<"This is function object"<<m_iX<<" "<<val<<std::endl; return m_iX<val; } }; int CountLessThanFive(const std::vector<int>& v, const IntCompare& tmp) { int count{0}; for(auto& a:v) { if(tmp(a)) //object(val) is calling functor ++count; } return count; } int main() { std::cout<<"functor"<<std::endl; IntCompare obj1{5}; //universal initialization //How to call function object bool res1= obj1(6); std::cout<<"5<6 expecting true and getting:"<<res1<<std::endl; bool res2= obj1(4); std::cout<<"5<4 expecting false and getting:"<<res2<<std::endl; //Actual Use case of functor std::vector<int>vec{1,2,3,4,5,6,7,8};//expecting count as 3 int count = CountLessThanFive(vec, obj1); std::cout<<"Count:"<<count<<std::endl; return 0; }
Output:
functor 5<6 expecting true and getting:1 5<4 expecting false and getting:0 Count:3